Here is a complete universal recursive solution.
This class will parse any XML under any structure, with or without tags, from the simplest to the most complex.
It saves all the correct values ββand converts them (bool, txt or int), generates adequate array keys for all groups of elements, including tags, saves duplicate elements, etc. etc.
Please forgive the stats, this is part of a large set of XML tools that I used before rewriting them all for HHVM or pthreads, I donβt have time to properly build this one, but it will work like a charm for simple PHP.
For tags, the declared value is "@attr" in this case, but may be any of your needs.
$xml = "<body> <users id='group 1'> <user>x</user> <user>y</user> <user>z</user> </users> <users id='group 2'> <user>x</user> <user>y</user> <user>z</user> </users> </body>"; $result = xml_utils::xml_to_array($xml);
result:
Array ( [users] => Array ( [0] => Array ( [user] => Array ( [0] => x [1] => y [2] => z ) [@attr] => Array ( [id] => group 1 ) ) [1] => Array ( [user] => Array ( [0] => x [1] => y [2] => z ) [@attr] => Array ( [id] => group 2 ) ) ) )
Grade:
class xml_utils { public static function objectToArray($object) { if (!is_object($object) && !is_array($object)) { return $object; } if (is_object($object)) { $object = get_object_vars($object); } return array_map('objectToArray', $object); } public static function xml_to_array($xmlstr) { $doc = new DOMDocument(); $doc->loadXML($xmlstr); return xml_utils::dom_to_array($doc->documentElement); } public static function dom_to_array($node) { $output = array(); switch ($node->nodeType) { case XML_CDATA_SECTION_NODE: case XML_TEXT_NODE: $output = trim($node->textContent); break; case XML_ELEMENT_NODE: for ($i = 0, $m = $node->childNodes->length; $i < $m; $i++) { $child = $node->childNodes->item($i); $v = xml_utils::dom_to_array($child); if (isset($child->tagName)) { $t = xml_utils::ConvertTypes($child->tagName); if (!isset($output[$t])) { $output[$t] = array(); } $output[$t][] = $v; } elseif ($v) { $output = (string) $v; } } if (is_array($output)) { if ($node->attributes->length) { $a = array(); foreach ($node->attributes as $attrName => $attrNode) { $a[$attrName] = xml_utils::ConvertTypes($attrNode->value); } $output['@attr'] = $a; } foreach ($output as $t => $v) { if (is_array($v) && count($v) == 1 && $t != '@attr') { $output[$t] = $v[0]; } } } break; } return $output; } public static function ConvertTypes($org) { if (is_numeric($org)) { $val = floatval($org); } else { if ($org === 'true') { $val = true; } else if ($org === 'false') { $val = false; } else { if ($org === '') { $val = null; } else { $val = $org; } } } return $val; } }
cpugourou
source share