php如何解释xml,PHP – 如何解析这个xml?
我正在嘗試解析下面的XML,以便最終得到一個看起來像樣本的數組……我很難弄清楚如何獲取標簽內部的屬性以輸出我想要的方式它…
XML
我想要的數組::注意添加的數組元素
Array
[cust] => Array
[rid] => 999999
[member_id] => 12345
[lname] => Doe
[fname] => John
[address] => Array
[0] => Array
[memberid] => 12345
[address1] => 1234 Mockingbird Lane
[address2] =>
[city] => Oakland
[state] => CA
[zip] => 91111
[country] => United States
[phone] => Array
[0] => Array
[memberid] => 12345
[phonenumber] => 415.555.1212
[countrycodeid] => 1
[phonetype] => Mobile
[custcode] => Array
[0] => Array
[memberid] => 12345
[ccode] => Silver
[deleted] => 1
[1] => Array
[memberid] => 12345
[ccode] => Gold
解決方法:
您可以使用DOMDocument及其字段/方法來提取數據.
DOMDocument也是DOMNode有一個名為attributes的字段,它是屬性名稱的映射和值的節點,因此您可以從中獲取屬性名稱和值(#6-9).
每個節點都有firstChild和next兄弟,你可以瀏覽所有子節點(#12-26).
從那以后,您可以相應地創建數據數組.這是我使用的代碼(稍作調整).
/*01*/ function Parse($XMLNode, $XMLData = null) {
/*02*/ if ($XMLData == null)
/*03*/ $XMLData = array();
/*04*/
/*05*/ // Extract attribute as the array values
/*06*/ if ($XMLNode->hasAttributes()) {
/*07*/ foreach ($XMLNode->attributes as $AttrName => $AttrNode)
/*08*/ $XMLData[$AttrName] = $AttrNode->nodeValue;
/*09*/ }
/*10*/
/*11*/ // Loop all child
/*12*/ $Child = $XMLNode->firstChild;
/*13*/ while ($Child != null) {
/*14*/ $Name = $Child->nodeName;
/*15*/ if ($Name != "#text") { // Ignore the text
/*16*/ $Nodes = $XMLData[$Name];
/*17*/ if ($Nodes == null)
/*18*/ $Nodes = array(); // Array value from subnode is a nest array
/*19*/
/*21*/ $Nodes[] = Parse($Child);
/*22*/ $XMLData[$Name] = $Nodes;
/*23*/ }
/*24*/
/*25*/ $Child = $Child->nextSibling;
/*26*/ }
/*27*/ return $XMLData;
/*28*/ }
/*29*/
/*31*/ $XML = <<
/*32*/
/*33*/
/*34*/
/*35*/
/*36*/
/*37*/
/*38*/ EOF;
/*39*/
/*41*/ $DOC = new DOMDocument();
/*42*/ $DOC->loadXML($XML);
/*43*/ $Data = Parse($DOC->firstChild);
/*44*/
/*45*/ print_r($Data);
上面的代碼按預期返回結果.
希望這可以幫助.
標簽:php,xml,parsing
來源: https://codeday.me/bug/20191003/1849723.html
總結
以上是生活随笔為你收集整理的php如何解释xml,PHP – 如何解析这个xml?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中国古诗词大全1000首名句
- 下一篇: php怎么使用多个数据库,怎么在php项