[英]Using DOMDocument PHP classes on simple XML file
我的XML文檔如下。
<?xml version="1.0" encoding="utf-8"?>
<userSettings>
<tables>
<table id="supertable">
<userTabLayout id="A">{"id":"colidgoeshereX"}</userTabLayout>
<userTabLayout id="B">{"id":"colidgoeshereY"}</userTabLayout>
</table>
<table id="almost-supertable">
<userTabLayout id="A">{"id":"colidgoeshereC"}</userTabLayout>
<userTabLayout id="B">{"id":"colidgoeshereD"}</userTabLayout>
</table>
</tables>
</userSettings>
我正在使用以下PHP代碼加載文件( DOMDocument
),然后使用DomXpath
遍歷文檔
<?php
...
$xmldoc = new DOMDocument();
$xmldoc->load ($filename);
$xpath = new DomXpath($xmldoc);
$x = $xpath->query("//tables/table");
$y = $x->item(0);
...
?>
現在, $y
變量包含一個DOMElement
對象,其nodeValue
屬性包含如下字符串:
["nodeValue"]=>
string(81) "
{"id":"colidgoeshereX"}
{"id":"colidgoeshereY"}
"
我的問題是, <userTabLayout>
節點發生了什么? 為什么我不將其視為<table>
節點的子節點? 如果我想訪問<userTabLayout id="B">
節點,該怎么做?
通常,我會閱讀有關此類內容的文檔,但是官方PHP頁面上的官方文檔確實很少。
好了,您無需DomXpath就可以工作。
$xmlS = '
<userSettings>
<tables>
<table id="supertable">
<userTabLayout id="A">{"id":"colidgoeshereX"}</userTabLayout>
<userTabLayout id="B">{"id":"colidgoeshereY"}</userTabLayout>
</table>
<table id="almost-supertable">
<userTabLayout id="A">{"id":"colidgoeshereC"}</userTabLayout>
<userTabLayout id="B">{"id":"colidgoeshereD"}</userTabLayout>
</table>
</tables>
</userSettings>
';
$xmldoc = new DOMDocument();
$xmldoc->loadXml($xmlS);
$table1 = $xmldoc->getElementsByTagName("tables")->item(0);
$userTabLayoutA = $table1->getElementsByTagName("userTabLayout")->item(0);
$userTabLayoutB = $table1->getElementsByTagName("userTabLayout")->item(1);
echo $userTabLayoutA->nodeValue; // {"id":"colidgoeshereX"}
echo $userTabLayoutB->nodeValue; // {"id":"colidgoeshereY"}
如您所見,您可以使用getElementsByTagName
並指定所需的項來逐個訪問所有元素。
我的問題是,
<userTabLayout>
節點發生了什么?
沒事 該<userTabLayout>
元素是你有一個DOMElement的子元素$y
。
為什么我不將其視為
<table>
節點的子節點?
因為您不是通過使用nodeValue
字段來尋找子節點。
如果我想訪問
<userTabLayout id="B">
節點,該怎么做?
通過遍歷文檔,例如,通過childNodes
字段(驚奇)訪問子節點。
通常,我會閱讀有關此類內容的文檔,但是官方PHP頁面上的官方文檔確實很少。
這是因為DOM是由W3C已經記錄在案,如這里: http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/
由於該鏈接是規范它可能是一個有點技術,所以更努力進入,但是可以考慮它完成(例如檢查真實性,如果你需要知道它)。 一旦了解到已指定DOM,您就可以與任何可用的DOM文檔相關,例如在MDN中,甚至在Javascript(W3C的兩個默認實現之一)中,它在PHP中的工作方式也相似(尤其是遍歷或Xpath的工作方式) 。
祝您閱讀愉快!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.