为什么 DOMXPath 不起作用?
我一直在尝试编写一个 PHP 脚本来使用 DOMXPath;然而我似乎遗漏了一些东西,因为我的 XPath 查询都没有返回任何内容。因此,我尝试淡化我的脚本来尝试解析一个非常基本的 XML 文档,但这也不起作用。我的脚本基于这个 XPath 示例。
<?php
$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$xml .= '<bookstore>';
$xml .= '<book category="COOKING">';
$xml .= '<title lang="en">Everyday Italian</title>';
$xml .= '<author>Giada De Laurentiis</author>';
$xml .= '<year>2005</year>';
$xml .= '<price>30.00</price>';
$xml .= '</book>';
$xml .= '</bookstore>';
$dom = new DOMDocument('1.0');
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$result = $xpath->query('/bookstore/book[1]/title');
var_dump($result);
?>
问题是我的 $result var_dump 总是 返回类似以下内容:
object(DOMNodeList)#4 (0) { }
...表明它什么也没找到。
I've been trying to write a PHP script to parse an XML document using DOMXPath; however it seems I'm missing something because none of my XPath queries are returning anything. So I've tried to water down my script to try and parse a very rudimentary XML document, and that's not working either. I've based this script off of this XPath example.
<?php
$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>';
$xml .= '<bookstore>';
$xml .= '<book category="COOKING">';
$xml .= '<title lang="en">Everyday Italian</title>';
$xml .= '<author>Giada De Laurentiis</author>';
$xml .= '<year>2005</year>';
$xml .= '<price>30.00</price>';
$xml .= '</book>';
$xml .= '</bookstore>';
$dom = new DOMDocument('1.0');
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$result = $xpath->query('/bookstore/book[1]/title');
var_dump($result);
?>
Problem is that my var_dump of $result always returns something like:
object(DOMNodeList)#4 (0) { }
...indicating that it found nothing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,var_dump() 的输出会产生误导。
尝试
或
替代。
例如使用您的代码(直到 $result = $xpath....)+
输出是
In this case the output of var_dump() is misleading.
Try
or
instead.
e.g. using your code (up until $result = $xpath....) +
the output is
我一直在努力处理在根节点中指定 xmlns="http://www.w3.org/2005/Atom" 的文档。把它拿出来,xpath就可以工作了。
I've struggled with a doc that specifies xmlns="http://www.w3.org/2005/Atom" in the root node. Took it out, and xpath works.