1: <?php
2: /**
3: * A parser for XML that uses SimpleXMLElement
4: *
5: * @package Elgg.Core
6: * @subpackage XML
7: */
8: class ElggXMLElement {
9: /**
10: * @var SimpleXMLElement
11: */
12: private $_element;
13:
14: /**
15: * Creates an ElggXMLParser from a string or existing SimpleXMLElement
16: *
17: * @param string|SimpleXMLElement $xml The XML to parse
18: */
19: public function __construct($xml) {
20: if ($xml instanceof SimpleXMLElement) {
21: $this->_element = $xml;
22: } else {
23: $this->_element = new SimpleXMLElement($xml);
24: }
25: }
26:
27: /**
28: * @return string The name of the element
29: */
30: public function getName() {
31: return $this->_element->getName();
32: }
33:
34: /**
35: * @return string[] The attributes
36: */
37: public function getAttributes() {
38: //include namespace declarations as attributes
39: $xmlnsRaw = $this->_element->getNamespaces();
40: $xmlns = array();
41: foreach ($xmlnsRaw as $key => $val) {
42: $label = 'xmlns' . ($key ? ":$key" : $key);
43: $xmlns[$label] = $val;
44: }
45: //get attributes and merge with namespaces
46: $attrRaw = $this->_element->attributes();
47: $attr = array();
48: foreach ($attrRaw as $key => $val) {
49: $attr[$key] = $val;
50: }
51: $attr = array_merge((array) $xmlns, (array) $attr);
52: $result = array();
53: foreach ($attr as $key => $val) {
54: $result[$key] = (string) $val;
55: }
56: return $result;
57: }
58:
59: /**
60: * @return string CData
61: */
62: public function getContent() {
63: return (string) $this->_element;
64: }
65:
66: /**
67: * @return ElggXMLElement[] Child elements
68: */
69: public function getChildren() {
70: $children = $this->_element->children();
71: $result = array();
72: foreach ($children as $val) {
73: $result[] = new ElggXMLElement($val);
74: }
75:
76: return $result;
77: }
78:
79: /**
80: * Override ->
81: *
82: * @param string $name Property name
83: * @return mixed
84: */
85: function __get($name) {
86: switch ($name) {
87: case 'name':
88: return $this->getName();
89: break;
90: case 'attributes':
91: return $this->getAttributes();
92: break;
93: case 'content':
94: return $this->getContent();
95: break;
96: case 'children':
97: return $this->getChildren();
98: break;
99: }
100: return null;
101: }
102:
103: /**
104: * Override isset
105: *
106: * @param string $name Property name
107: * @return boolean
108: */
109: function __isset($name) {
110: switch ($name) {
111: case 'name':
112: return $this->getName() !== null;
113: break;
114: case 'attributes':
115: return $this->getAttributes() !== null;
116: break;
117: case 'content':
118: return $this->getContent() !== null;
119: break;
120: case 'children':
121: return $this->getChildren() !== null;
122: break;
123: }
124: return false;
125: }
126:
127: }