php xml 转换 数组

3 篇文章 0 订阅
class XmlUtils
{
    public static function xmlStr2Array($str)
    {
        $sxe = new SimpleXMLElement($str);
        return  self::xml2Array($sxe);
    }

    private static function xml2Array($sxe)
    {
        $arr = array();
        if($sxe instanceof SimpleXMLElement) {
            $name = $sxe->getName();
            if(!empty($name)) {
                    $arr[$name] = array();
                $attrs = $sxe->attributes();
                foreach($attrs as $key => $value) {
                    if(!empty($key)) {
                        $arr[$name]['attr_'.$key] = (string)$value;
                    }
                }
                $children = $sxe->children();
                if(is_null($children) || count($children) == 0) {
                    //echo '<br>' . trim((string)($sxe->asXML())) . '<br>';
//                    if(0 == count($attrs)) {
//                        $arr[$name] = trim((string)($sxe->asXML()));
//                    } else {
                        $arr[$name]['value'] = trim((string)($sxe->asXML()));
//                    }
                } else {
                    foreach($children as $child) {
                        $childName = $child->getName();
                        if(!empty($childName)) {
                            $childArr = $this->xml2Array($child);
                            $key = $childName;
                            $i = 1;
                            while(array_key_exists($key, $arr[$name])) {
                                $key = $childName . $i;
                            }
                            $arr[$name][$key] = $childArr[$childName];
                        }
                    }
                }
            }
        }
        return $arr;
    }
}
$result = XmlUtils::xmlStr2Array($result);
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值