鍍金池/ 問答/PHP  HTML/ php 處理有層次的xml數(shù)據(jù)

php 處理有層次的xml數(shù)據(jù)

通過simplexml_load_string處理后數(shù)據(jù)
圖片描述

接口返回數(shù)據(jù):
圖片描述

處理這種xml 數(shù)據(jù) 想得到里面的節(jié)點的值, 請問一下大神們 應(yīng)該怎么處理

<?xml version='1.0' standalone='yes' charset='gb2312'?><CommPara><ItemPara><ParaRow><retCode>0</retCode><retstr>成功</retstr><VipName>臨時會員</VipName><CertNo></CertNo><Mobile></Mobile><retBalance>198770.0000</retBalance><retJF>3916.5000</retJF><retTxt></retTxt></ParaRow></ItemPara></CommPara>

回答
編輯回答
夢一場

PHP本身就提供了一些庫來操作XML,手冊:
http://www.php.net/manual/zh/...

  • DOMDocument

  • ML Expat Parser

  • SimpleXML

  • XMLReader

  • ...

參考一下文章例子
http://blog.csdn.net/aloneswo...

自己看看用什么方法來解析~


哪里解決不了?
比如這樣吧,遍歷層層解析:

<?php
header("Content-type:text/html; Charset=utf-8");

$content = "
<commpara>
  <itempara>
    <pararow>
      <retcode>0</retcode>
      <retstr>成功</retstr>
    </pararow>
  </itempara>
</commpara>
";

// $xml = simplexml_load_file("test.xml");
$xml = simplexml_load_string($content);

echo '第一層:' . $xml->getName() . "<br />";

foreach($xml->children() as $child){
    echo '第二層:' . $child->getName(). "<br />";

    foreach($child->children() as $subChild){
        echo '第三層:' . $subChild->getName() . "<br />";

        foreach($subChild->children() as $item){
            echo $item->getName() . ": " . $item . "<br />";
        }
    }
}

輸出:

第一層:commpara
第二層:itempara
第三層:pararow
retcode: 0
retstr: 成功

更簡單粗暴的XML轉(zhuǎn)數(shù)組,這樣子:

$content = "
<commpara>
  <itempara>
    <pararow>
      <retcode>0</retcode>
      <retstr>成功</retstr>
    </pararow>
  </itempara>
</commpara>
";

$xml = simplexml_load_string($content);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
print_r($array);

輸出,直接就是個數(shù)組:

Array
(
    [itempara] => Array
        (
            [pararow] => Array
                (
                    [retcode] => 0
                    [retstr] => 成功
                )

        )

)
2017年8月1日 09:40