php xml array 互相转换

原创
2018/03/19 17:12
阅读数 633

    function xml2arr($xml)
    {
        $obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $json = json_encode($obj);
        $arr = json_decode($json, true);
        return $arr;
    }

    function arr2xml($root_element_name,$ar)
    {
        $xml = new \SimpleXMLElement("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
        $f = create_function('$f,$c,$a',' 
            foreach($a as $k=>$v) { 
                if(is_array($v)) { 
                    $ch=$c->addChild($k); 
                    $f($f,$ch,$v); 
                } else { 
                    $c->addChild($k,$v); 
                } 
            }');
        $f($f,$xml,$ar);
        return $xml->asXML();
    }

arr2xml方法有个bug,因为array的下标不能同名,但xml的子元素是可以同名的,如<peoples><people>...</people>...</peoples>,peoples里面有多个people元素,此时php声明数组时,下标必须不同,如$peoples['people_1']=[],$peoples['people_2']=[]来创建,而不能$peoples['people']=[],$peoples['people']=[]来定义两个元素,所有在调用arr2xml之后,要将_1或_2之类的下标替换掉,如$xml = preg_replace('/\_\d+\>/','',$xml);

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部