Home  >  Article  >  Backend Development  >  Convert SimpleXMLElement object to PHP array_PHP tutorial

Convert SimpleXMLElement object to PHP array_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 14:58:50838browse

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/363778.htmlTechArticlePHP provides the simplexml_load_string method to parse XML format strings and return SimpleXMLElement objects. However, general arrays are more applicable, so there will also be conversions to ordinary...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn