+ -
当前位置:首页 → 问答吧 → xml转换成数组的问题

xml转换成数组的问题

时间:2011-12-28

来源:互联网

现有如下xml:
XML code

<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属性,想转换成如下数组,有什么好办法吗
PHP code

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
        )
        .....
)


作者: Mr_merlin   发布时间: 2011-12-28

看看这个

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

作者: happypiggy2010   发布时间: 2011-12-28

引用 1 楼 happypiggy2010 的回复:

看看这个

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


上面的方法用下面两行就能实现,但还是满足不了我的需要

PHP code

$obj=simplexml_load_string($xml);
$arr=json_decode(json_encode($obj),TRUE);

作者: Mr_merlin   发布时间: 2011-12-28

PHP code
$s =<<< 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;
$obj = simplexml_load_string($s);
$r = array();
foreach($obj as $name=>$nodes) {
  foreach($nodes as $k=>$v) {
    $t = (array)$v->attributes()->text;
    $r[$name][$k] = $t[0];
  }
}
print_r($r);

PHP code
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
        )

)


作者: xuzuning   发布时间: 2011-12-28