简体   繁体   English

为什么DOMXPath不起作用?

[英]Why doesn't DOMXPath work?

I've been trying to write a PHP script to parse an XML document using DOMXPath ; 我一直在尝试编写PHP脚本来使用DOMXPath解析XML文档。 however it seems I'm missing something because none of my XPath queries are returning anything. 但是似乎丢失了一些东西,因为我的XPath查询都没有返回任何东西。 So I've tried to water down my script to try and parse a very rudimentary XML document, and that's not working either. 因此,我试图减少我的脚本来尝试解析一个非常基本的XML文档,但这也不起作用。 I've based this script off of this XPath example . 我已经基于该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);

?>

Problem is that my var_dump of $result always returns something like: 问题是我的$ result var_dump 总是返回如下内容:

object(DOMNodeList)#4 (0) { }

...indicating that it found nothing. 表示它什么也没发现。

In this case the output of var_dump() is misleading. 在这种情况下,var_dump()的输出会产生误导。 Try 尝试

foreach($result as $e) {
  echo $e->nodeValue;
}

or 要么

echo $result->length;

instead. 代替。

eg using your code (up until $result = $xpath....) + 例如,使用您的代码(直到$ result = $ xpath ....)+

echo phpversion(), "\n";
var_dump($result);
echo $result->length, "\n";
foreach($result as $e) {
  echo $e->nodeValue;
}

the output is 输出是

5.3.1
object(DOMNodeList)#4 (0) {
}
1
Everyday Italian

I've struggled with a doc that specifies xmlns="http://www.w3.org/2005/Atom" in the root node. 我一直在努力寻找一个在根节点中指定xmlns =“ http://www.w3.org/2005/Atom”的文档。 Took it out, and xpath works. 拿出来,xpath就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM