Home > Backend Development > PHP Tutorial > xml转换成数组的有关问题

xml转换成数组的有关问题

WBOY
Release: 2016-06-13 13:37:28
Original
718 people have browsed it

xml转换成数组的问题
现有如下xml:

XML code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
<root>
<rows>
<errmsg text=""></errmsg>
<retvalue text="true"></retvalue>
</rows>
<records>
<productno text="000321"></productno>
<billno text=""></billno>
<orderno text="D004410439"></orderno>
<out_trade_no text="100001"></out_trade_no>
<plcprem text="0.0"></plcprem>
<orderprem text="50.0"></orderprem>
<commision text="0.0"></commision>
</records>
....
<root>

</root></root>
Copy after login

xml深度不确定但每个节点都有text属性,想转换成如下数组,有什么好办法吗
PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

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


Copy after login


------解决方案--------------------
看看这个

http://weblog.thomassmart.com/2008/09/php-function-xml2array/
------解决方案--------------------
PHP code
$s =
<rows>
<errmsg text=""></errmsg>
<retvalue text="true"></retvalue>
</rows>
<records>
<productno text="000321"></productno>
<billno text=""></billno>
<orderno text="D004410439"></orderno>
<out_trade_no text="100001"></out_trade_no>
<plcprem text="0.0"></plcprem>
<orderprem text="50.0"></orderprem>
<commision text="0.0"></commision>
</records>

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);
<br><font color="#e78608">------解决方案--------------------</font><br>
Copy after login
探讨
PHP code
$s =









……
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template