我对如何从xpath查询中提取数据感到困惑。我使用的是PHP 5.5.6,我得到了这个结果:
I'm all the countries:
DOMNodeList Object
(
[length] => 0
)
1
I'm all the countries:
DOMNodeList Object
(
[length] => 0
)
1
I'm all the countries:
DOMNodeList Object
(
[length] => 0
)
1
I'm all the countries:
DOMNodeList Object
(
[length] => 0
)
1
我的XML文件被截断(仅显示第一部分,我正在尝试使用大型XML文件):
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Data>
<NewDataSet>
<Table>
<Country>Philippines</Country>
<City>Subic Bay Weather Station</City>
</Table>
<Table>
<Country>Philippines</Country>
<City>Laoag</City>
</Table>
<Table>
<Country>Philippines</Country>
<City>Ninoy Aquino Inter-National Airport</City>
</Table>
<Table>
<Country>Philippines</Country>
<City>Davao Airport</City>
</Table>
<Table>
<Country>Philippines</Country>
<City>Clark Ab</City>
</Table>
<Table>
<Country>Philippines</Country>
<City>Legaspi</City>
</Table>
<Table>
<Country>Philippines</Country>
<City>Romblon</City>
</Table>
我想要做的就是通过xpath查询显示Country标签内的内容。我的代码是:
<?php
$reader = new XMLReader();
$reader->open("countries.xml", "UTF-8");
while($reader->read()){
//echo var_dump($reader->nodeType), "<br/>";
if($reader->nodeType == XMLReader::ELEMENT && $reader->localName == "Table"){
$node = $reader->expand();
$dom = new DOMDocument;
$xp = new DomXPath($dom);
$xp1 = $xp->query("//Country");
echo "I'm all the countries: <pre>",print_r($xp1),"</pre>";
}
}
$reader->close();
?>
我不明白为什么我没有获得$ xp1的价值,我只能使用$xp1->nodeValue
或$xp1->item(0)->nodeValue
。我确实尝试过,即使返回的对象只有&#34;长度&#34;回馈。我正在查看this site上的示例清单5,看起来我应该能够做到这一点。我错过了什么?
答案 0 :(得分:1)
您的DOM为空,您永远不会向其添加$node
。尝试:
$reader = new XMLReader();
$reader->open("countries.xml", "UTF-8");
while($reader->read()){
if($reader->nodeType == XMLReader::ELEMENT && $reader->localName == "Table"){
$node = $reader->expand();
$dom = new DOMDocument;
$n = $dom->importNode($node, true);
$dom->appendChild($n);
$xp = new DomXPath($dom);
$xp1 = $xp->query("//Country");
echo "I'm all the countries: <pre>{$xp1->item(0)->nodeValue}</pre>";
}
}
$reader->close();