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;
}
}
来源:芒果小站
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号