简体   繁体   中英

PHP XML Libraries Not Returning XPath Results

I am trying to use PHP and XPath to grab all the Category nodes with an ID element of 1364 from this XML: http://education.oracle.co.uk/html/oracle/28US/schedule.xml

My code is currently looking like this:

$schedule = new SimpleXMLElement("schedule.xml", null, true);
$nodes = $schedule->xpath("//category[id=1364]");
if(!$nodes) {
    echo "No xpath results.";
} else {
    echo count($nodes)." results.";
}

The XPath returns no results. I have checked the query using other XPath query programs, and a result was returned.

The above code uses SimpleXML, but I have experienced exactly the same problem when using DOMDocument. In both SimpleXML and DOMDocument, running an XPath of "//*" works, returning all nodes in the document.

Thanks!

A wild guess, this is a namespace issue

Your XML document probably contains something like this

<root xmlns="http://some.uri">
    <category id="1364"/>
</root>

Because <category> is in the default namespace it does not have any prefix but in order to your XPath to work, you need to bind also this namespace to some prefix and then use that prefix in your XPath expression.

$schedule->registerXPathNamespace("ns", "http://some.uri");
$nodes = $schedule->xpath('//ns:category[id=1364]');

XPath (1.0) expressions without a namespace prefix always match only to targets in no-namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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