现有如下xml:<root>
<rows>
<errMsg text=""/>
<retValue text="true"/>
</rows>
<records>
<productno text="000321"/>
<billno text=""/>
<orderno text="D004410439"/>
<out_trade_no text="100001"/>
<plcprem text="0.0"/>
<orderprem text="50.0"/>
<commision text="0.0"/>
</records>
....
<root>xml深度不确定但每个节点都有text属性,想转换成如下数组,有什么好办法吗Array
(
    [rows] => Array
        (
            [errMsg] => 
            [retValue] => true
        )
    [records] => Array
        (
            [productno] =>000321
            [billno] =>
            [orderno] =>D004410439
            [out_trade_no] => 100001
            [plcprem] =>0.0
            [orderprem] =>50.0
            [commision] =>0.0
        )
        .....
)

解决方案 »

  1.   

    看看这个http://weblog.thomassmart.com/2008/09/php-function-xml2array/
      

  2.   


    上面的方法用下面两行就能实现,但还是满足不了我的需要
    $obj=simplexml_load_string($xml);
    $arr=json_decode(json_encode($obj),TRUE);
      

  3.   

    本帖最后由 xuzuning 于 2011-12-28 14:56:22 编辑
      

  4.   


    缺少一点。如果records有多个的话。。
      

  5.   

    呵呵,既然楼主没有给出 records有多个 时的样式
    那么又何必画蛇添足呢?
      

  6.   


    后面还有节点,而且节点深度再增加,有没有什么完美的解决方案呢?比如下面的:<root>
    <rows>
    <errMsg text=""/>
    <retValue text="true"/>
    </rows>
    <records>
    <productno text="000321"/>
    <billno text=""/>
    <orderno text="D004410439"/>
    <out_trade_no text="100001"/>
    <plcprem text="0.0"/>
    <orderprem text="50.0"/>
    <commision text="0.0"/>
    </records>
    <plcinfo>
    <productno text="000321"/>
    <productname text="途牛交通意外险"/>
    <companyno text="0014"/>
    <companyname text="永诚财产保险上海分公司"/>
    <plcsubj text=""/>
    <plcstarttime text="2011-12-29 00:00:00"/>
    <plcendtime text="2012-01-04 23:59:59"/>
    <count text="2"/>
    <insurants>
    <plcno text="1036706542011200248"/>
    <isdname text="张三"/>
    <cardtype text="身份证"/>
    <cardno text="456789789789"/>
    <addr text="上海市虹桥路333号"/>
    <re1 text="xxxxx"/>
    <re2 text="yyyyyyy"/>
    </insurants>
    <insurants>
    <plcno text="1036706542011200249"/>
    <isdname text="张三"/>
    <cardtype text="身份证"/>
    <cardno text="45645645645654"/>
    <addr text="上海市虹桥路333号"/>
    <re1 text="xxxxx"/>
    <re2 text="yyyyyyy"/>
    </insurants>
    </plcinfo>
    </root>
      

  7.   

    问题解决,用正则替换的方法:$obj=simplexml_load_string($xml);
    $json=json_encode($obj);
    $json=preg_replace_callback('/{"@attributes":{"text":"([^}]*)"}}/',
    create_function('$matches','return "\"".$matches[1]."\"";'),
    $json);
    $arr=json_decode($json,true);或者:$xml=preg_replace_callback('/<([^ ]*) text="([^"]*)" \/>/',
    create_function(
    '$matches',
    'return "<".$matches[1].">".$matches[2]."</".$matches[1].">";'
    ),$xml);
    $obj=simplexml_load_string($xml);
    $arr=json_decode(json_encode($obj),true);