现有如下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
)
.....
)
<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
)
.....
)
上面的方法用下面两行就能实现,但还是满足不了我的需要
$obj=simplexml_load_string($xml);
$arr=json_decode(json_encode($obj),TRUE);
缺少一点。如果records有多个的话。。
那么又何必画蛇添足呢?
后面还有节点,而且节点深度再增加,有没有什么完美的解决方案呢?比如下面的:<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>
$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);