Provides two parameters, the first parameter is a SimpleXMLElement object, and the second parameter is a Boolean value that controls whether the final return value contains the root node.
The code is as follows |
Copy Code |
function Xmltoarr ($xml, $root = True) { if (! $xml->children ()) { Return (string) $xml; } $array = Array (); foreach ($xml->children () as $element => $node) { $totalElement = count ($xml->{$element}); if (!isset ($array [$element])) { $array [$element] = ""; } Has attributes if ($attributes = $node->attributes ()) { $data = Array ( ' Attributes ' => array (), ' Value ' => (count ($node) > 0)? $this->__xmltoarr ($node, False) : (String) $node ); foreach ($attributes as $attr => $value) { $data [' Attributes '] [$attr] = (string) $value; } if ($totalElement > 1) { $array [$element] = $data; } else { $array [$element] = $data; } Just a value } else { if ($totalElement > 1) { $array [$element] = $this->__xmltoarr ($node, false); } else { $array [$element] = $this->__xmltoarr ($node, false); } } } if ($root) { Return Array ($xml->getname () => $array); } else { return $array; } } |