Home > php教程 > php手册 > 将 SimpleXMLElement 对象转换为 PHP 数组

将 SimpleXMLElement 对象转换为 PHP 数组

WBOY
Release: 2016-06-13 11:41:09
Original
851 people have browsed it

PHP 提供了 simplexml_load_string 方法用来解析 XML 格式的字符串,并返回 SimpleXMLElement 对象。不过一般数组是更为适用的,所以也会有转换为普通数组的需求,这个方法测试完全奏效,支持 SimpleXMLElement 对象多层嵌套的情况。

提供两个参数,第一个参数为 SimpleXMLElement 对象,第二个参数为布尔值,控制最终返回值是否包含根节点。

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:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template