3 * @file src/Util/XML.php
5 namespace Friendica\Util;
7 use Friendica\Core\Logger;
12 * @brief This class contain methods to work with XML data
17 * @brief Creates an XML structure out of a given array
19 * @param array $array The array of the XML structure that will be generated
20 * @param object $xml The createdXML will be returned by reference
21 * @param bool $remove_header Should the XML header be removed or not?
22 * @param array $namespaces List of namespaces
23 * @param bool $root interally used parameter. Mustn't be used from outside.
25 * @return string The created XML
27 public static function fromArray($array, &$xml, $remove_header = false, $namespaces = [], $root = true)
30 foreach ($array as $key => $value) {
31 foreach ($namespaces as $nskey => $nsvalue) {
32 $key .= " xmlns".($nskey == "" ? "":":").$nskey.'="'.$nsvalue.'"';
35 if (is_array($value)) {
36 $root = new SimpleXMLElement("<".$key."/>");
37 self::fromArray($value, $root, $remove_header, $namespaces, false);
39 $root = new SimpleXMLElement("<".$key.">".self::escape($value)."</".$key.">");
42 $dom = dom_import_simplexml($root)->ownerDocument;
43 $dom->formatOutput = true;
46 $xml_text = $dom->saveXML();
49 $xml_text = trim(substr($xml_text, 21));
57 foreach ($array as $key => $value) {
58 if (!isset($element) && isset($xml)) {
62 if (is_integer($key)) {
63 if (isset($element)) {
64 if (is_scalar($value)) {
67 /// @todo: handle nested array values
73 $element_parts = explode(":", $key);
74 if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) {
75 $namespace = $namespaces[$element_parts[0]];
76 } elseif (isset($namespaces[""])) {
77 $namespace = $namespaces[""];
82 // Remove undefined namespaces from the key
83 if ((count($element_parts) > 1) && is_null($namespace)) {
84 $key = $element_parts[1];
87 if (substr($key, 0, 11) == "@attributes") {
88 if (!isset($element) || !is_array($value)) {
92 foreach ($value as $attr_key => $attr_value) {
93 $element_parts = explode(":", $attr_key);
94 if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) {
95 $namespace = $namespaces[$element_parts[0]];
100 $element->addAttribute($attr_key, $attr_value, $namespace);
106 if (!is_array($value)) {
107 $element = $xml->addChild($key, self::escape($value), $namespace);
108 } elseif (is_array($value)) {
109 $element = $xml->addChild($key, null, $namespace);
110 self::fromArray($value, $element, $remove_header, $namespaces, false);
116 * @brief Copies an XML object
118 * @param object $source The XML source
119 * @param object $target The XML target
120 * @param string $elementname Name of the XML element of the target
123 public static function copy(&$source, &$target, $elementname)
125 if (count($source->children()) == 0) {
126 $target->addChild($elementname, self::escape($source));
128 $child = $target->addChild($elementname);
129 foreach ($source->children() as $childfield => $childentry) {
130 self::copy($childentry, $child, $childfield);
136 * @brief Create an XML element
138 * @param \DOMDocument $doc XML root
139 * @param string $element XML element name
140 * @param string $value XML value
141 * @param array $attributes array containing the attributes
143 * @return \DOMElement XML element object
145 public static function createElement(\DOMDocument $doc, $element, $value = "", $attributes = [])
147 $element = $doc->createElement($element, self::escape($value));
149 foreach ($attributes as $key => $value) {
150 $attribute = $doc->createAttribute($key);
151 $attribute->value = self::escape($value);
152 $element->appendChild($attribute);
158 * @brief Create an XML and append it to the parent object
160 * @param \DOMDocument $doc XML root
161 * @param object $parent parent object
162 * @param string $element XML element name
163 * @param string $value XML value
164 * @param array $attributes array containing the attributes
167 public static function addElement(\DOMDocument $doc, $parent, $element, $value = "", $attributes = [])
169 $element = self::createElement($doc, $element, $value, $attributes);
170 $parent->appendChild($element);
174 * @brief Convert an XML document to a normalised, case-corrected array
177 * @param object $xml_element The XML document
178 * @param integer $recursion_depth recursion counter for internal use - default 0
179 * internal use, recursion counter
181 * @return array | string The array from the xml element or the string
183 public static function elementToArray($xml_element, &$recursion_depth = 0)
185 // If we're getting too deep, bail out
186 if ($recursion_depth > 512) {
190 $xml_element_copy = '';
191 if (!is_string($xml_element)
192 && !is_array($xml_element)
193 && (get_class($xml_element) == 'SimpleXMLElement')
195 $xml_element_copy = $xml_element;
196 $xml_element = get_object_vars($xml_element);
199 if (is_array($xml_element)) {
201 if (count($xml_element) <= 0) {
202 return (trim(strval($xml_element_copy)));
205 foreach ($xml_element as $key => $value) {
207 $result_array[strtolower($key)] = self::elementToArray($value, $recursion_depth);
211 if ($recursion_depth == 0) {
212 $temp_array = $result_array;
214 strtolower($xml_element_copy->getName()) => $temp_array,
218 return ($result_array);
220 return (trim(strval($xml_element)));
225 * @brief Convert the given XML text to an array in the XML structure.
227 * Xml::toArray() will convert the given XML text to an array in the XML structure.
228 * Link: http://www.bin-co.com/php/scripts/xml2array/
229 * Portions significantly re-written by mike@macgirvin.com for Friendica
230 * (namespaces, lowercase tags, get_attribute default changed, more...)
232 * Examples: $array = Xml::toArray(file_get_contents('feed.xml'));
233 * $array = Xml::toArray(file_get_contents('feed.xml', true, 1, 'attribute'));
235 * @param object $contents The XML text
236 * @param boolean $namespaces True or false include namespace information
237 * in the returned array as array elements.
238 * @param integer $get_attributes 1 or 0. If this is 1 the function will get the attributes as well as the tag values -
239 * this results in a different array structure in the return value.
240 * @param string $priority Can be 'tag' or 'attribute'. This will change the way the resulting
241 * array sturcture. For 'tag', the tags are given more importance.
243 * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
246 public static function toArray($contents, $namespaces = true, $get_attributes = 1, $priority = 'attribute')
252 if (!function_exists('xml_parser_create')) {
253 Logger::log('Xml::toArray: parser function missing');
258 libxml_use_internal_errors(true);
259 libxml_clear_errors();
262 $parser = @xml_parser_create_ns("UTF-8", ':');
264 $parser = @xml_parser_create();
268 Logger::log('Xml::toArray: xml_parser_create: no resource');
272 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
273 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
274 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
275 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
276 @xml_parse_into_struct($parser, trim($contents), $xml_values);
277 @xml_parser_free($parser);
280 Logger::log('Xml::toArray: libxml: parse error: ' . $contents, Logger::DATA);
281 foreach (libxml_get_errors() as $err) {
282 Logger::log('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, Logger::DATA);
284 libxml_clear_errors();
291 $current = &$xml_array; // Reference
293 // Go through the tags.
294 $repeated_tag_index = []; // Multiple tags with same name will be turned into an array
295 foreach ($xml_values as $data) {
297 $type = $data['type'];
298 $level = $data['level'];
299 $attributes = isset($data['attributes']) ? $data['attributes'] : null;
300 $value = isset($data['value']) ? $data['value'] : null;
303 $attributes_data = [];
306 if ($priority == 'tag') {
309 $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
313 //Set the attributes too.
314 if (isset($attributes) and $get_attributes) {
315 foreach ($attributes as $attr => $val) {
316 if ($priority == 'tag') {
317 $attributes_data[$attr] = $val;
319 $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
324 // See tag status and do the needed.
325 if ($namespaces && strpos($tag, ':')) {
326 $namespc = substr($tag, 0, strrpos($tag, ':'));
327 $tag = strtolower(substr($tag, strlen($namespc)+1));
328 $result['@namespace'] = $namespc;
330 $tag = strtolower($tag);
332 if ($type == "open") { // The starting of the tag '<tag>'
333 $parent[$level-1] = &$current;
334 if (!is_array($current) || (!in_array($tag, array_keys($current)))) { // Insert New tag
335 $current[$tag] = $result;
336 if ($attributes_data) {
337 $current[$tag. '_attr'] = $attributes_data;
339 $repeated_tag_index[$tag.'_'.$level] = 1;
341 $current = &$current[$tag];
342 } else { // There was another element with the same tag name
344 if (isset($current[$tag][0])) { // If there is a 0th element it is already an array
345 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
346 $repeated_tag_index[$tag.'_'.$level]++;
347 } else { // This section will make the value an array if multiple tags with the same name appear together
348 $current[$tag] = [$current[$tag], $result]; // This will combine the existing item and the new item together to make an array
349 $repeated_tag_index[$tag.'_'.$level] = 2;
351 if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
352 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
353 unset($current[$tag.'_attr']);
356 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
357 $current = &$current[$tag][$last_item_index];
359 } elseif ($type == "complete") { // Tags that ends in 1 line '<tag />'
360 //See if the key is already taken.
361 if (!isset($current[$tag])) { //New Key
362 $current[$tag] = $result;
363 $repeated_tag_index[$tag.'_'.$level] = 1;
364 if ($priority == 'tag' and $attributes_data) {
365 $current[$tag. '_attr'] = $attributes_data;
367 } else { // If taken, put all things inside a list(array)
368 if (isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
370 // ...push the new element into that array.
371 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
373 if ($priority == 'tag' and $get_attributes and $attributes_data) {
374 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
376 $repeated_tag_index[$tag.'_'.$level]++;
377 } else { // If it is not an array...
378 $current[$tag] = [$current[$tag], $result]; //...Make it an array using using the existing value and the new value
379 $repeated_tag_index[$tag.'_'.$level] = 1;
380 if ($priority == 'tag' and $get_attributes) {
381 if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
383 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
384 unset($current[$tag.'_attr']);
387 if ($attributes_data) {
388 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
391 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
394 } elseif ($type == 'close') { // End of tag '</tag>'
395 $current = &$parent[$level-1];
403 * @brief Delete a node in a XML object
405 * @param \DOMDocument $doc XML document
406 * @param string $node Node name
409 public static function deleteNode(\DOMDocument $doc, $node)
411 $xpath = new DOMXPath($doc);
412 $list = $xpath->query("//".$node);
413 foreach ($list as $child) {
414 $child->parentNode->removeChild($child);
418 public static function parseString($s, $strict = true)
420 // the "strict" parameter is deactivated
421 libxml_use_internal_errors(true);
423 $x = @simplexml_load_string($s);
425 Logger::log('libxml: parse: error: ' . $s, Logger::DATA);
426 foreach (libxml_get_errors() as $err) {
427 Logger::log('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, Logger::DATA);
429 libxml_clear_errors();
434 public static function getFirstNodeValue(DOMXPath $xpath, $element, $context = null)
436 $result = $xpath->evaluate($element, $context);
437 if (!is_object($result)) {
441 $first_item = $result->item(0);
442 if (!is_object($first_item)) {
446 return $first_item->nodeValue;
449 public static function getFirstAttributes(DOMXPath $xpath, $element, $context = null)
451 $result = $xpath->query($element, $context);
452 if (!is_object($result)) {
456 $first_item = $result->item(0);
457 if (!is_object($first_item)) {
461 return $first_item->attributes;
465 * escape text ($str) for XML transport
467 * @return string Escaped text.
469 public static function escape($str)
471 $buffer = htmlspecialchars($str, ENT_QUOTES, "UTF-8");
472 $buffer = trim($buffer);
479 * @param string $s xml escaped text
480 * @return string unescaped text
482 public static function unescape($s)
484 $ret = htmlspecialchars_decode($s, ENT_QUOTES);
489 * apply escape() to all values of array $val, recursively
493 public static function arrayEscape($val)
496 return $val?"true":"false";
497 } elseif (is_array($val)) {
498 return array_map('XML::arrayEscape', $val);
500 return self::escape((string) $val);