3 * @file include/xml.php
8 * @brief This class contain functions to work with XML data
13 * @brief Creates an XML structure out of a given array
15 * @param array $array The array of the XML structure that will be generated
16 * @param object $xml The createdXML will be returned by reference
17 * @param bool $remove_header Should the XML header be removed or not?
18 * @param array $namespaces List of namespaces
19 * @param bool $root - interally used parameter. Mustn't be used from outside.
21 * @return string The created XML
23 public static function from_array($array, &$xml, $remove_header = false, $namespaces = array(), $root = true) {
26 foreach($array as $key => $value) {
27 foreach ($namespaces AS $nskey => $nsvalue)
28 $key .= " xmlns".($nskey == "" ? "":":").$nskey.'="'.$nsvalue.'"';
30 $root = new SimpleXMLElement("<".$key."/>");
31 self::from_array($value, $root, $remove_header, $namespaces, false);
33 $dom = dom_import_simplexml($root)->ownerDocument;
34 $dom->formatOutput = true;
37 $xml_text = $dom->saveXML();
40 $xml_text = trim(substr($xml_text, 21));
46 foreach($array as $key => $value) {
47 if ($key == "@attributes") {
48 if (!isset($element) OR !is_array($value))
51 foreach ($value as $attr_key => $attr_value) {
52 $element_parts = explode(":", $attr_key);
53 if ((count($element_parts) > 1) AND isset($namespaces[$element_parts[0]]))
54 $namespace = $namespaces[$element_parts[0]];
58 $element->addAttribute ($attr_key, $attr_value, $namespace);
64 $element_parts = explode(":", $key);
65 if ((count($element_parts) > 1) AND isset($namespaces[$element_parts[0]]))
66 $namespace = $namespaces[$element_parts[0]];
70 if (!is_array($value))
71 $element = $xml->addChild($key, xmlify($value), $namespace);
72 elseif (is_array($value)) {
73 $element = $xml->addChild($key, NULL, $namespace);
74 self::from_array($value, $element, $remove_header, $namespaces, false);
80 * @brief Copies an XML object
82 * @param object $source The XML source
83 * @param object $target The XML target
84 * @param string $elementname Name of the XML element of the target
86 public static function copy(&$source, &$target, $elementname) {
87 if (count($source->children()) == 0)
88 $target->addChild($elementname, xmlify($source));
90 $child = $target->addChild($elementname);
91 foreach ($source->children() AS $childfield => $childentry)
92 self::copy($childentry, $child, $childfield);
97 * @brief Create an XML element
99 * @param object $doc XML root
100 * @param string $element XML element name
101 * @param string $value XML value
102 * @param array $attributes array containing the attributes
104 * @return object XML element object
106 public static function create_element($doc, $element, $value = "", $attributes = array()) {
107 $element = $doc->createElement($element, xmlify($value));
109 foreach ($attributes AS $key => $value) {
110 $attribute = $doc->createAttribute($key);
111 $attribute->value = xmlify($value);
112 $element->appendChild($attribute);
118 * @brief Create an XML and append it to the parent object
120 * @param object $doc XML root
121 * @param object $parent parent object
122 * @param string $element XML element name
123 * @param string $value XML value
124 * @param array $attributes array containing the attributes
126 public static function add_element($doc, $parent, $element, $value = "", $attributes = array()) {
127 $element = self::create_element($doc, $element, $value, $attributes);
128 $parent->appendChild($element);
132 * @brief Convert an XML document to a normalised, case-corrected array
135 * @param object $xml_element The XML document
136 * @param integer $recursion_depth recursion counter for internal use - default 0
137 * internal use, recursion counter
139 * @return array | sring The array from the xml element or the string
141 public static function element_to_array($xml_element, &$recursion_depth=0) {
143 // If we're getting too deep, bail out
144 if ($recursion_depth > 512) {
148 if (!is_string($xml_element) &&
149 !is_array($xml_element) &&
150 (get_class($xml_element) == 'SimpleXMLElement')) {
151 $xml_element_copy = $xml_element;
152 $xml_element = get_object_vars($xml_element);
155 if (is_array($xml_element)) {
156 $result_array = array();
157 if (count($xml_element) <= 0) {
158 return (trim(strval($xml_element_copy)));
161 foreach($xml_element as $key=>$value) {
164 $result_array[strtolower($key)] =
165 self::element_to_array($value, $recursion_depth);
168 if ($recursion_depth == 0) {
169 $temp_array = $result_array;
170 $result_array = array(
171 strtolower($xml_element_copy->getName()) => $temp_array,
175 return ($result_array);
178 return (trim(strval($xml_element)));
183 * @brief Convert the given XML text to an array in the XML structure.
185 * xml::to_array() will convert the given XML text to an array in the XML structure.
186 * Link: http://www.bin-co.com/php/scripts/xml2array/
187 * Portions significantly re-written by mike@macgirvin.com for Friendica
188 * (namespaces, lowercase tags, get_attribute default changed, more...)
190 * Examples: $array = xml::to_array(file_get_contents('feed.xml'));
191 * $array = xml::to_array(file_get_contents('feed.xml', true, 1, 'attribute'));
193 * @param object $contents The XML text
194 * @param boolean $namespaces True or false include namespace information
195 * in the returned array as array elements.
196 * @param integer $get_attributes 1 or 0. If this is 1 the function will get the attributes as well as the tag values -
197 * this results in a different array structure in the return value.
198 * @param string $priority Can be 'tag' or 'attribute'. This will change the way the resulting
199 * array sturcture. For 'tag', the tags are given more importance.
201 * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
203 public static function to_array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
204 if(!$contents) return array();
206 if(!function_exists('xml_parser_create')) {
207 logger('xml::to_array: parser function missing');
212 libxml_use_internal_errors(true);
213 libxml_clear_errors();
216 $parser = @xml_parser_create_ns("UTF-8",':');
218 $parser = @xml_parser_create();
221 logger('xml::to_array: xml_parser_create: no resource');
225 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
226 // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
227 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
228 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
229 @xml_parse_into_struct($parser, trim($contents), $xml_values);
230 @xml_parser_free($parser);
233 logger('xml::to_array: libxml: parse error: ' . $contents, LOGGER_DATA);
234 foreach(libxml_get_errors() as $err)
235 logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
236 libxml_clear_errors();
241 $xml_array = array();
243 $opened_tags = array();
246 $current = &$xml_array; // Reference
248 // Go through the tags.
249 $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
250 foreach($xml_values as $data) {
251 unset($attributes,$value); // Remove existing values, or there will be trouble
253 // This command will extract these variables into the foreach scope
254 // tag(string), type(string), level(int), attributes(array).
255 extract($data); // We could use the array by itself, but this cooler.
258 $attributes_data = array();
261 if($priority == 'tag') $result = $value;
262 else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
265 //Set the attributes too.
266 if(isset($attributes) and $get_attributes) {
267 foreach($attributes as $attr => $val) {
268 if($priority == 'tag') $attributes_data[$attr] = $val;
269 else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
273 // See tag status and do the needed.
274 if($namespaces && strpos($tag,':')) {
275 $namespc = substr($tag,0,strrpos($tag,':'));
276 $tag = strtolower(substr($tag,strlen($namespc)+1));
277 $result['@namespace'] = $namespc;
279 $tag = strtolower($tag);
281 if($type == "open") { // The starting of the tag '<tag>'
282 $parent[$level-1] = &$current;
283 if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
284 $current[$tag] = $result;
285 if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
286 $repeated_tag_index[$tag.'_'.$level] = 1;
288 $current = &$current[$tag];
290 } else { // There was another element with the same tag name
292 if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
293 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
294 $repeated_tag_index[$tag.'_'.$level]++;
295 } else { // This section will make the value an array if multiple tags with the same name appear together
296 $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
297 $repeated_tag_index[$tag.'_'.$level] = 2;
299 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
300 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
301 unset($current[$tag.'_attr']);
305 $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
306 $current = &$current[$tag][$last_item_index];
309 } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
310 //See if the key is already taken.
311 if(!isset($current[$tag])) { //New Key
312 $current[$tag] = $result;
313 $repeated_tag_index[$tag.'_'.$level] = 1;
314 if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
316 } else { // If taken, put all things inside a list(array)
317 if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
319 // ...push the new element into that array.
320 $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
322 if($priority == 'tag' and $get_attributes and $attributes_data) {
323 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
325 $repeated_tag_index[$tag.'_'.$level]++;
327 } else { // If it is not an array...
328 $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
329 $repeated_tag_index[$tag.'_'.$level] = 1;
330 if($priority == 'tag' and $get_attributes) {
331 if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
333 $current[$tag]['0_attr'] = $current[$tag.'_attr'];
334 unset($current[$tag.'_attr']);
337 if($attributes_data) {
338 $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
341 $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
345 } elseif($type == 'close') { // End of tag '</tag>'
346 $current = &$parent[$level-1];