Search code examples
phpxpathdomdocumentdomxpath

Why doesn't DOMXPath work?


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.


Solution

  • 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