【发布时间】:2017-04-25 22:30:04
【问题描述】:
这让我发疯了。在我的 XML 文件中,我嵌套了同名 <entry> 的子级,并且我试图只获得顶层。如果我打电话给getElementsByTagName(),它会抓住所有这些,所以我正在解析直接孩子,但似乎没有任何工作正常。
<locations>
<devices>
<entry>
<a/>
<b/>
<c>
<entry>
..
</entry>
</c>
</entry>
<entry>
<a/>
<b/>
<c>
<entry>
..
</entry>
</c>
</entry>
</devices>
</locations>
<?
$path = "Export.txt" ;
$xml = file_get_contents( $path );
$dom = new DOMDocument( '1.0', 'utf-8' );
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
// use it as a source
$dom->loadXML($xml) ;
// grab all "devices" should ONLY be 1 device
$devices = $dom->getElementsByTagName('devices');
$entries = array() ;
// parse through each FIRST child...which should be the first level <entry>
// however, the below is empty.
for ($i = 0; $i < $devices->childNodes->length; ++$i) {
echo $count++ ;
$entries[] = $devices->childNodes->item($i);
}
// but I get the following error on this foreach:
// Warning: Invalid argument supplied for foreach() in process.php
foreach ($devices->childNodes as $node) {
echo "This: " . $count++ ;
}
// this prints "1": which is correct.
echo sizeof($devices) ;
//关于从childNode中提取getElementsByTag的额外问题
foreach ($devices as $device) {
foreach($device->childNodes as $child) { // this should be each parent <entry>
$thisC = $child->getElementsByTagName('c') ; // this should be only <c> tags BUT THIS NEVER SEEMS TO WORK
foreach ($thisC->childNodes as $subEntry) {
echo $subEntry->nodeValue ;
}
}
}
【问题讨论】:
标签: php xml domdocument getelementsbytagname child-nodes