开发者

Why doesn't DOMXPath work?

开发者 https://www.devze.com 2022-12-14 14:37 出处:网络
I\'ve been trying to write a PHP script to parse 开发者_StackOverflowan XML document using DOMXPath; however it seems I\'m missing something because none of my XPath queries are returning anything. So

I've been trying to write a PHP script to parse 开发者_StackOverflowan 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.


In this case the output of var_dump() is misleading. Try

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

or

echo $result->length;

instead.

e.g. using your code (up until $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. Took it out, and xpath works.

0

精彩评论

暂无评论...
验证码 换一张
取 消