4 * @file include/xml.php
9 * @brief This class contain methods to work with XML data
14 * @brief Creates an XML structure out of a given array
16 * @param array $array The array of the XML structure that will be generated
17 * @param object $xml The createdXML will be returned by reference
18 * @param bool $remove_header Should the XML header be removed or not?
19 * @param array $namespaces List of namespaces
20 * @param bool $root - interally used parameter. Mustn't be used from outside.
22 * @return string The created XML
24 public static function from_array($array, &$xml, $remove_header = false, $namespaces = array(), $root = true) {
27 foreach ($array as $key => $value) {
28 foreach ($namespaces AS $nskey => $nsvalue) {
29 $key .= " xmlns".($nskey == "" ? "":":").$nskey.'="'.$nsvalue.'"';
32 if (is_array($value)) {
33 $root = new SimpleXMLElement("<".$key."/>");
34 self::from_array($value, $root, $remove_header, $namespaces, false);
36 $root = new SimpleXMLElement("<".$key.">".xmlify($value)."</".$key.">");
39 $dom = dom_import_simplexml($root)->ownerDocument;
40 $dom->formatOutput = true;
43 $xml_text = $dom->saveXML();
46 $xml_text = trim(substr($xml_text, 21));
53 foreach($array as $key => $value) {
54 if (!isset($element) AND isset($xml)) {
58 if (is_integer($key)) {
59 if (isset($element)) {
60 if (is_scalar($value)) {
63 /// @todo: handle nested array values
69 $element_parts = explode(":", $key);
70 if ((count($element_parts) > 1) AND isset($namespaces[$element_parts[0]])) {
71 $namespace = $namespaces[$element_parts[0]];
72 } elseif (isset($namespaces[""])) {
73 $namespace = $namespaces[""];
78 // Remove undefined namespaces from the key
79 if ((count($element_parts) > 1) AND is_null($namespace)) {
80 $key = $element_parts[1];
83 if (substr($key, 0, 11) == "@attributes") {
84 if (!isset($element) OR !is_array($value)) {
88 foreach ($value as $attr_key => $attr_value) {
89 $element_parts = explode(":", $attr_key);
90 if ((count($element_parts) > 1) AND isset($namespaces[$element_parts[0]])) {
91 $namespace = $namespaces[$element_parts[0]];
96 $element->addAttribute($attr_key, $attr_value, $namespace);
102 if (!is_array($value)) {
103 $element = $xml->addChild($key, xmlify($value), $namespace);
104 } elseif (is_array($value)) {
105 $element = $xml->addChild($key, NULL, $namespace);
106 self::from_array($value, $element, $remove_header, $namespaces, false);
112 * @brief Copies an XML object
114 * @param object $source The XML source
115 * @param object $target The XML target
116 * @param string $elementname Name of the XML element of the target
118 public static function copy(&$source, &$target, $elementname) {
119 if (count($source->children()) == 0)
120 $target->addChild($elementname, xmlify($source));
122 $child = $target->addChild($elementname);
123 foreach ($source->children() AS $childfield => $childentry) {
124 self::copy($childentry, $child, $childfield);
130 * @brief Create an XML element
132 * @param object $doc XML root
133 * @param string $element XML element name
134 * @param string $value XML value
135 * @param array $attributes array containing the attributes
137 * @return object XML element object
139 public static function create_element($doc, $element, $value = "", $attributes = array()) {
140 $element = $doc->createElement($element, xmlify($value));
142 foreach ($attributes AS $key => $value) {
143 $attribute = $doc->createAttribute($key);
144 $attribute->value = xmlify($value);
145 $element->appendChild($attribute);
151 * @brief Create an XML and append it to the parent object
153 * @param object $doc XML root
154 * @param object $parent parent object
155 * @param string $element XML element name
156 * @param string $value XML value
157 * @param array $attributes array containing the attributes
159 public static function add_element($doc, $parent, $element, $value = "", $attributes = array()) {
160 $element = self::create_element($doc, $element, $value, $attributes);
161 $parent->appendChild($element);
165 * @brief Convert an XML document to a normalised, case-corrected array
168 * @param object $xml_element The XML document
169 * @param integer $recursion_depth recursion counter for internal use - default 0
170 * internal use, recursion counter
172 * @return array | sring The array from the xml element or the string
174 public static function element_to_array($xml_element, &$recursion_depth=0) {
176 // If we're getting too deep, bail out
177 if ($recursion_depth > 512) {
181 if (!is_string($xml_element)
182 && !is_array($xml_element)
183 && (get_class($xml_element) == 'SimpleXMLElement')) {
184 $xml_element_copy = $xml_element;
185 $xml_element = get_object_vars($xml_element);
188 if (is_array($xml_element)) {
189 $result_array = array();
190 if (count($xml_element) <= 0) {
191 return (trim(strval($xml_element_copy)));
194 foreach ($xml_element as $key => $value) {
197 $result_array[strtolower($key)] =
198 self::element_to_array($value, $recursion_depth);
201 if ($recursion_depth == 0) {
202 $temp_array = $result_array;
203 $result_array = array(
204 strtolower($xml_element_copy->getName()) => $temp_array,
208 return ($result_array);
211 return (trim(strval($xml_element)));
216 * @brief Convert the given XML text to an array in the XML structure.
218 * xml::to_array() will convert the given XML text to an array in the XML structure.
219 * Link: http://www.bin-co.com/php/scripts/xml2array/
220 * Portions significantly re-written by mike@macgirvin.com for Friendica
221 * (namespaces, lowercase tags, get_attribute default changed, more...)
223 * Examples: $array = xml::to_array(file_get_contents('feed.xml'));
224 * $array = xml::to_array(file_get_contents('feed.xml', true, 1, 'attribute'));
226 * @param object $contents The XML text
227 * @param boolean $namespaces True or false include namespace information
228 * in the returned array as array elements.
229 * @param integer $get_attributes 1 or 0. If this is 1 the function will get the attributes as well as the tag values -
230 * this results in a different array structure in the return value.
231 * @param string $priority Can be 'tag' or 'attribute'. This will change the way the resulting
232 * array sturcture. For 'tag', the tags are given more importance.
234 * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
236 public static function to_array($contents, $namespaces = true, $get_attributes = 1, $priority = 'attribute') {
241 if (!function_exists('xml_parser_create')) {
242 logger('xml::to_array: parser function missing');
247 libxml_use_internal_errors(true);
248 libxml_clear_errors();
251 $parser = @xml_parser_create_ns("UTF-8",':');
253 $parser = @xml_parser_create();
257 logger('xml::to_array: xml_parser_create: no resource');
261 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
262 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
263 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
264 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
265 @xml_parse_into_struct($parser, trim($contents), $xml_values);
266 @xml_parser_free($parser);
269 logger('xml::to_array: libxml: parse error: ' . $contents, LOGGER_DATA);
270 foreach (libxml_get_errors() as $err) {
271 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
273 libxml_clear_errors();
278 $xml_array = array();
280 $opened_tags = array();
283 $current = &$xml_array; // Reference
285 // Go through the tags.
286 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
287 foreach ($xml_values as $data) {
288 unset($attributes, $value); // Remove existing values, or there will be trouble
290 // This command will extract these variables into the foreach scope
291 // tag(string), type(string), level(int), attributes(array).
292 extract($data); // We could use the array by itself, but this cooler.
295 $attributes_data = array();
298 if ($priority == 'tag') {
301 $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
305 //Set the attributes too.
306 if (isset($attributes) and $get_attributes) {
307 foreach ($attributes as $attr => $val) {
308 if($priority == 'tag') {
309 $attributes_data[$attr] = $val;
311 $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
316 // See tag status and do the needed.
317 if ($namespaces && strpos($tag, ':')) {
318 $namespc = substr($tag, 0, strrpos($tag, ':'));
319 $tag = strtolower(substr($tag, strlen($namespc)+1));
320 $result['@namespace'] = $namespc;
322 $tag = strtolower($tag);
324 if ($type == "open") { // The starting of the tag '<tag>'
325 $parent[$level-1] = &$current;
326 if (!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
327 $current[$tag] = $result;
328 if ($attributes_data) {
329 $current[$tag. '_attr'] = $attributes_data;
331 $repeated_tag_index[$tag.'_'.$level] = 1;
333 $current = &$current[$tag];
335 } else { // There was another element with the same tag name
337 if (isset($current[$tag][0])) { // If there is a 0th element it is already an array
338 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
339 $repeated_tag_index[$tag.'_'.$level]++;
340 } else { // This section will make the value an array if multiple tags with the same name appear together
341 $current[$tag] = array($current[$tag], $result); // This will combine the existing item and the new item together to make an array
342 $repeated_tag_index[$tag.'_'.$level] = 2;
344 if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
345 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
346 unset($current[$tag.'_attr']);
350 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
351 $current = &$current[$tag][$last_item_index];
354 } elseif ($type == "complete") { // Tags that ends in 1 line '<tag />'
355 //See if the key is already taken.
356 if (!isset($current[$tag])) { //New Key
357 $current[$tag] = $result;
358 $repeated_tag_index[$tag.'_'.$level] = 1;
359 if ($priority == 'tag' and $attributes_data) {
360 $current[$tag. '_attr'] = $attributes_data;
363 } else { // If taken, put all things inside a list(array)
364 if (isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
366 // ...push the new element into that array.
367 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
369 if ($priority == 'tag' and $get_attributes and $attributes_data) {
370 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
372 $repeated_tag_index[$tag.'_'.$level]++;
374 } else { // If it is not an array...
375 $current[$tag] = array($current[$tag], $result); //...Make it an array using using the existing value and the new value
376 $repeated_tag_index[$tag.'_'.$level] = 1;
377 if ($priority == 'tag' and $get_attributes) {
378 if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
380 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
381 unset($current[$tag.'_attr']);
384 if ($attributes_data) {
385 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
388 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
392 } elseif ($type == 'close') { // End of tag '</tag>'
393 $current = &$parent[$level-1];
401 * @brief Delete a node in a XML object
403 * @param object $doc XML document
404 * @param string $node Node name
406 public static function deleteNode(&$doc, $node) {
407 $xpath = new DomXPath($doc);
408 $list = $xpath->query("//".$node);
409 foreach ($list as $child) {
410 $child->parentNode->removeChild($child);