4 * @file src/Util/XML.php
6 namespace Friendica\Util;
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 from_array($array, &$xml, $remove_header = false, $namespaces = array(), $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::from_array($value, $root, $remove_header, $namespaces, false);
39 $root = new SimpleXMLElement("<".$key.">".xmlify($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));
56 foreach ($array as $key => $value) {
57 if (!isset($element) && isset($xml)) {
61 if (is_integer($key)) {
62 if (isset($element)) {
63 if (is_scalar($value)) {
66 /// @todo: handle nested array values
72 $element_parts = explode(":", $key);
73 if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) {
74 $namespace = $namespaces[$element_parts[0]];
75 } elseif (isset($namespaces[""])) {
76 $namespace = $namespaces[""];
81 // Remove undefined namespaces from the key
82 if ((count($element_parts) > 1) && is_null($namespace)) {
83 $key = $element_parts[1];
86 if (substr($key, 0, 11) == "@attributes") {
87 if (!isset($element) || !is_array($value)) {
91 foreach ($value as $attr_key => $attr_value) {
92 $element_parts = explode(":", $attr_key);
93 if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) {
94 $namespace = $namespaces[$element_parts[0]];
99 $element->addAttribute($attr_key, $attr_value, $namespace);
105 if (!is_array($value)) {
106 $element = $xml->addChild($key, xmlify($value), $namespace);
107 } elseif (is_array($value)) {
108 $element = $xml->addChild($key, null, $namespace);
109 self::from_array($value, $element, $remove_header, $namespaces, false);
115 * @brief Copies an XML object
117 * @param object $source The XML source
118 * @param object $target The XML target
119 * @param string $elementname Name of the XML element of the target
121 public static function copy(&$source, &$target, $elementname)
123 if (count($source->children()) == 0) {
124 $target->addChild($elementname, xmlify($source));
126 $child = $target->addChild($elementname);
127 foreach ($source->children() as $childfield => $childentry) {
128 self::copy($childentry, $child, $childfield);
134 * @brief Create an XML element
136 * @param object $doc XML root
137 * @param string $element XML element name
138 * @param string $value XML value
139 * @param array $attributes array containing the attributes
141 * @return object XML element object
143 public static function create_element($doc, $element, $value = "", $attributes = array())
145 $element = $doc->createElement($element, xmlify($value));
147 foreach ($attributes as $key => $value) {
148 $attribute = $doc->createAttribute($key);
149 $attribute->value = xmlify($value);
150 $element->appendChild($attribute);
156 * @brief Create an XML and append it to the parent object
158 * @param object $doc XML root
159 * @param object $parent parent object
160 * @param string $element XML element name
161 * @param string $value XML value
162 * @param array $attributes array containing the attributes
164 public static function add_element($doc, $parent, $element, $value = "", $attributes = array())
166 $element = self::create_element($doc, $element, $value, $attributes);
167 $parent->appendChild($element);
171 * @brief Convert an XML document to a normalised, case-corrected array
174 * @param object $xml_element The XML document
175 * @param integer $recursion_depth recursion counter for internal use - default 0
176 * internal use, recursion counter
178 * @return array | sring The array from the xml element or the string
180 public static function element_to_array($xml_element, &$recursion_depth=0)
182 // If we're getting too deep, bail out
183 if ($recursion_depth > 512) {
187 if (!is_string($xml_element)
188 && !is_array($xml_element)
189 && (get_class($xml_element) == 'SimpleXMLElement')
191 $xml_element_copy = $xml_element;
192 $xml_element = get_object_vars($xml_element);
195 if (is_array($xml_element)) {
196 $result_array = array();
197 if (count($xml_element) <= 0) {
198 return (trim(strval($xml_element_copy)));
201 foreach ($xml_element as $key => $value) {
203 $result_array[strtolower($key)] = self::element_to_array($value, $recursion_depth);
207 if ($recursion_depth == 0) {
208 $temp_array = $result_array;
209 $result_array = array(
210 strtolower($xml_element_copy->getName()) => $temp_array,
214 return ($result_array);
216 return (trim(strval($xml_element)));
221 * @brief Convert the given XML text to an array in the XML structure.
223 * Xml::to_array() will convert the given XML text to an array in the XML structure.
224 * Link: http://www.bin-co.com/php/scripts/xml2array/
225 * Portions significantly re-written by mike@macgirvin.com for Friendica
226 * (namespaces, lowercase tags, get_attribute default changed, more...)
228 * Examples: $array = Xml::to_array(file_get_contents('feed.xml'));
229 * $array = Xml::to_array(file_get_contents('feed.xml', true, 1, 'attribute'));
231 * @param object $contents The XML text
232 * @param boolean $namespaces True or false include namespace information
233 * in the returned array as array elements.
234 * @param integer $get_attributes 1 or 0. If this is 1 the function will get the attributes as well as the tag values -
235 * this results in a different array structure in the return value.
236 * @param string $priority Can be 'tag' or 'attribute'. This will change the way the resulting
237 * array sturcture. For 'tag', the tags are given more importance.
239 * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
241 public static function to_array($contents, $namespaces = true, $get_attributes = 1, $priority = 'attribute')
247 if (!function_exists('xml_parser_create')) {
248 logger('Xml::to_array: parser function missing');
253 libxml_use_internal_errors(true);
254 libxml_clear_errors();
257 $parser = @xml_parser_create_ns("UTF-8", ':');
259 $parser = @xml_parser_create();
263 logger('Xml::to_array: xml_parser_create: no resource');
267 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
268 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
269 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
270 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
271 @xml_parse_into_struct($parser, trim($contents), $xml_values);
272 @xml_parser_free($parser);
275 logger('Xml::to_array: libxml: parse error: ' . $contents, LOGGER_DATA);
276 foreach (libxml_get_errors() as $err) {
277 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
279 libxml_clear_errors();
284 $xml_array = array();
286 $opened_tags = array();
289 $current = &$xml_array; // Reference
291 // Go through the tags.
292 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
293 foreach ($xml_values as $data) {
294 unset($attributes, $value); // Remove existing values, or there will be trouble
296 // This command will extract these variables into the foreach scope
297 // tag(string), type(string), level(int), attributes(array).
298 extract($data); // We could use the array by itself, but this cooler.
301 $attributes_data = array();
304 if ($priority == 'tag') {
307 $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
311 //Set the attributes too.
312 if (isset($attributes) and $get_attributes) {
313 foreach ($attributes as $attr => $val) {
314 if ($priority == 'tag') {
315 $attributes_data[$attr] = $val;
317 $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
322 // See tag status and do the needed.
323 if ($namespaces && strpos($tag, ':')) {
324 $namespc = substr($tag, 0, strrpos($tag, ':'));
325 $tag = strtolower(substr($tag, strlen($namespc)+1));
326 $result['@namespace'] = $namespc;
328 $tag = strtolower($tag);
330 if ($type == "open") { // The starting of the tag '<tag>'
331 $parent[$level-1] = &$current;
332 if (!is_array($current) || (!in_array($tag, array_keys($current)))) { // Insert New tag
333 $current[$tag] = $result;
334 if ($attributes_data) {
335 $current[$tag. '_attr'] = $attributes_data;
337 $repeated_tag_index[$tag.'_'.$level] = 1;
339 $current = &$current[$tag];
340 } else { // There was another element with the same tag name
342 if (isset($current[$tag][0])) { // If there is a 0th element it is already an array
343 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
344 $repeated_tag_index[$tag.'_'.$level]++;
345 } else { // This section will make the value an array if multiple tags with the same name appear together
346 $current[$tag] = array($current[$tag], $result); // This will combine the existing item and the new item together to make an array
347 $repeated_tag_index[$tag.'_'.$level] = 2;
349 if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
350 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
351 unset($current[$tag.'_attr']);
354 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
355 $current = &$current[$tag][$last_item_index];
357 } elseif ($type == "complete") { // Tags that ends in 1 line '<tag />'
358 //See if the key is already taken.
359 if (!isset($current[$tag])) { //New Key
360 $current[$tag] = $result;
361 $repeated_tag_index[$tag.'_'.$level] = 1;
362 if ($priority == 'tag' and $attributes_data) {
363 $current[$tag. '_attr'] = $attributes_data;
365 } else { // If taken, put all things inside a list(array)
366 if (isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
368 // ...push the new element into that array.
369 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
371 if ($priority == 'tag' and $get_attributes and $attributes_data) {
372 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
374 $repeated_tag_index[$tag.'_'.$level]++;
375 } else { // If it is not an array...
376 $current[$tag] = array($current[$tag], $result); //...Make it an array using using the existing value and the new value
377 $repeated_tag_index[$tag.'_'.$level] = 1;
378 if ($priority == 'tag' and $get_attributes) {
379 if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
381 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
382 unset($current[$tag.'_attr']);
385 if ($attributes_data) {
386 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
389 $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)
408 $xpath = new DomXPath($doc);
409 $list = $xpath->query("//".$node);
410 foreach ($list as $child) {
411 $child->parentNode->removeChild($child);