Home > Article > Backend Development > Convert SimpleXMLElement object to PHP array_PHP tutorial
PHP provides the simplexml_load_string method to parse XML format strings and return SimpleXMLElement objects. However, general arrays are more suitable, so there will also be a need to convert to ordinary arrays. This method is fully tested and supports multi-level nesting of SimpleXMLElement objects.
Provides two parameters, the first parameter is a SimpleXMLElement object, and the second parameter is a Boolean value, controlling whether the final return value contains the root node.
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;
}
}
Source: Mango Station