3 * @file src/Util/XML.php
5 namespace Friendica\Util;
11 * @brief This class contain methods to work with XML data
16 * @brief Creates an XML structure out of a given array
18 * @param array $array The array of the XML structure that will be generated
19 * @param object $xml The createdXML will be returned by reference
20 * @param bool $remove_header Should the XML header be removed or not?
21 * @param array $namespaces List of namespaces
22 * @param bool $root interally used parameter. Mustn't be used from outside.
24 * @return string The created XML
26 public static function fromArray($array, &$xml, $remove_header = false, $namespaces = array(), $root = true)
29 foreach ($array as $key => $value) {
30 foreach ($namespaces as $nskey => $nsvalue) {
31 $key .= " xmlns".($nskey == "" ? "":":").$nskey.'="'.$nsvalue.'"';
34 if (is_array($value)) {
35 $root = new SimpleXMLElement("<".$key."/>");
36 self::fromArray($value, $root, $remove_header, $namespaces, false);
38 $root = new SimpleXMLElement("<".$key.">".xmlify($value)."</".$key.">");
41 $dom = dom_import_simplexml($root)->ownerDocument;
42 $dom->formatOutput = true;
45 $xml_text = $dom->saveXML();
48 $xml_text = trim(substr($xml_text, 21));
55 foreach ($array as $key => $value) {
56 if (!isset($element) && isset($xml)) {
60 if (is_integer($key)) {
61 if (isset($element)) {
62 if (is_scalar($value)) {
65 /// @todo: handle nested array values
71 $element_parts = explode(":", $key);
72 if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) {
73 $namespace = $namespaces[$element_parts[0]];
74 } elseif (isset($namespaces[""])) {
75 $namespace = $namespaces[""];
80 // Remove undefined namespaces from the key
81 if ((count($element_parts) > 1) && is_null($namespace)) {
82 $key = $element_parts[1];
85 if (substr($key, 0, 11) == "@attributes") {
86 if (!isset($element) || !is_array($value)) {
90 foreach ($value as $attr_key => $attr_value) {
91 $element_parts = explode(":", $attr_key);
92 if ((count($element_parts) > 1) && isset($namespaces[$element_parts[0]])) {
93 $namespace = $namespaces[$element_parts[0]];
98 $element->addAttribute($attr_key, $attr_value, $namespace);
104 if (!is_array($value)) {
105 $element = $xml->addChild($key, xmlify($value), $namespace);
106 } elseif (is_array($value)) {
107 $element = $xml->addChild($key, null, $namespace);
108 self::fromArray($value, $element, $remove_header, $namespaces, false);
114 * @brief Copies an XML object
116 * @param object $source The XML source
117 * @param object $target The XML target
118 * @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 createElement($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
165 public static function addElement($doc, $parent, $element, $value = "", $attributes = array())
167 $element = self::createElement($doc, $element, $value, $attributes);
168 $parent->appendChild($element);
172 * @brief Convert an XML document to a normalised, case-corrected array
175 * @param object $xml_element The XML document
176 * @param integer $recursion_depth recursion counter for internal use - default 0
177 * internal use, recursion counter
179 * @return array | sring The array from the xml element or the string
181 public static function elementToArray($xml_element, &$recursion_depth = 0)
183 // If we're getting too deep, bail out
184 if ($recursion_depth > 512) {
188 if (!is_string($xml_element)
189 && !is_array($xml_element)
190 && (get_class($xml_element) == 'SimpleXMLElement')
192 $xml_element_copy = $xml_element;
193 $xml_element = get_object_vars($xml_element);
196 if (is_array($xml_element)) {
197 $result_array = array();
198 if (count($xml_element) <= 0) {
199 return (trim(strval($xml_element_copy)));
202 foreach ($xml_element as $key => $value) {
204 $result_array[strtolower($key)] = self::elementToArray($value, $recursion_depth);
208 if ($recursion_depth == 0) {
209 $temp_array = $result_array;
210 $result_array = array(
211 strtolower($xml_element_copy->getName()) => $temp_array,
215 return ($result_array);
217 return (trim(strval($xml_element)));
222 * @brief Convert the given XML text to an array in the XML structure.
224 * Xml::toArray() will convert the given XML text to an array in the XML structure.
225 * Link: http://www.bin-co.com/php/scripts/xml2array/
226 * Portions significantly re-written by mike@macgirvin.com for Friendica
227 * (namespaces, lowercase tags, get_attribute default changed, more...)
229 * Examples: $array = Xml::toArray(file_get_contents('feed.xml'));
230 * $array = Xml::toArray(file_get_contents('feed.xml', true, 1, 'attribute'));
232 * @param object $contents The XML text
233 * @param boolean $namespaces True or false include namespace information
234 * in the returned array as array elements.
235 * @param integer $get_attributes 1 or 0. If this is 1 the function will get the attributes as well as the tag values -
236 * this results in a different array structure in the return value.
237 * @param string $priority Can be 'tag' or 'attribute'. This will change the way the resulting
238 * array sturcture. For 'tag', the tags are given more importance.
240 * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
242 public static function toArray($contents, $namespaces = true, $get_attributes = 1, $priority = 'attribute')
248 if (!function_exists('xml_parser_create')) {
249 logger('Xml::toArray: parser function missing');
254 libxml_use_internal_errors(true);
255 libxml_clear_errors();
258 $parser = @xml_parser_create_ns("UTF-8", ':');
260 $parser = @xml_parser_create();
264 logger('Xml::toArray: xml_parser_create: no resource');
268 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
269 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
270 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
271 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
272 @xml_parse_into_struct($parser, trim($contents), $xml_values);
273 @xml_parser_free($parser);
276 logger('Xml::toArray: libxml: parse error: ' . $contents, LOGGER_DATA);
277 foreach (libxml_get_errors() as $err) {
278 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
280 libxml_clear_errors();
285 $xml_array = array();
287 $opened_tags = array();
290 $current = &$xml_array; // Reference
292 // Go through the tags.
293 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
294 foreach ($xml_values as $data) {
295 unset($attributes, $value); // Remove existing values, or there will be trouble
297 // This command will extract these variables into the foreach scope
298 // tag(string), type(string), level(int), attributes(array).
299 extract($data); // We could use the array by itself, but this cooler.
302 $attributes_data = array();
305 if ($priority == 'tag') {
308 $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
312 //Set the attributes too.
313 if (isset($attributes) and $get_attributes) {
314 foreach ($attributes as $attr => $val) {
315 if ($priority == 'tag') {
316 $attributes_data[$attr] = $val;
318 $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
323 // See tag status and do the needed.
324 if ($namespaces && strpos($tag, ':')) {
325 $namespc = substr($tag, 0, strrpos($tag, ':'));
326 $tag = strtolower(substr($tag, strlen($namespc)+1));
327 $result['@namespace'] = $namespc;
329 $tag = strtolower($tag);
331 if ($type == "open") { // The starting of the tag '<tag>'
332 $parent[$level-1] = &$current;
333 if (!is_array($current) || (!in_array($tag, array_keys($current)))) { // Insert New tag
334 $current[$tag] = $result;
335 if ($attributes_data) {
336 $current[$tag. '_attr'] = $attributes_data;
338 $repeated_tag_index[$tag.'_'.$level] = 1;
340 $current = &$current[$tag];
341 } else { // There was another element with the same tag name
343 if (isset($current[$tag][0])) { // If there is a 0th element it is already an array
344 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
345 $repeated_tag_index[$tag.'_'.$level]++;
346 } else { // This section will make the value an array if multiple tags with the same name appear together
347 $current[$tag] = array($current[$tag], $result); // This will combine the existing item and the new item together to make an array
348 $repeated_tag_index[$tag.'_'.$level] = 2;
350 if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
351 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
352 unset($current[$tag.'_attr']);
355 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
356 $current = &$current[$tag][$last_item_index];
358 } elseif ($type == "complete") { // Tags that ends in 1 line '<tag />'
359 //See if the key is already taken.
360 if (!isset($current[$tag])) { //New Key
361 $current[$tag] = $result;
362 $repeated_tag_index[$tag.'_'.$level] = 1;
363 if ($priority == 'tag' and $attributes_data) {
364 $current[$tag. '_attr'] = $attributes_data;
366 } else { // If taken, put all things inside a list(array)
367 if (isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
369 // ...push the new element into that array.
370 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
372 if ($priority == 'tag' and $get_attributes and $attributes_data) {
373 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
375 $repeated_tag_index[$tag.'_'.$level]++;
376 } else { // If it is not an array...
377 $current[$tag] = array($current[$tag], $result); //...Make it an array using using the existing value and the new value
378 $repeated_tag_index[$tag.'_'.$level] = 1;
379 if ($priority == 'tag' and $get_attributes) {
380 if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
382 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
383 unset($current[$tag.'_attr']);
386 if ($attributes_data) {
387 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
390 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
393 } elseif ($type == 'close') { // End of tag '</tag>'
394 $current = &$parent[$level-1];
402 * @brief Delete a node in a XML object
404 * @param object $doc XML document
405 * @param string $node Node name
408 public static function deleteNode(&$doc, $node)
410 $xpath = new DomXPath($doc);
411 $list = $xpath->query("//".$node);
412 foreach ($list as $child) {
413 $child->parentNode->removeChild($child);