加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

将 SimpleXMLElement 对象转换为 PHP 数组

发布时间:2020-12-13 20:40:19 所属栏目:PHP教程 来源:网络整理
导读:PHP 提供了 simplexml_load_string 方法用来解析 XML 格式的字符串,并返回 SimpleXMLElement 对象。不过一般数组是更为适用的,所以也会有转换为普通数组的需求,这个方法测试完全奏效,支持 SimpleXMLElement 对象多层嵌套的情况。 提供两个参数,第一个参

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;
}

}

来源:芒果小站

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读