XPath Queries 1

One of the most powerful parts of the DOM extension, is its integration with XPath—in fact, DomXpath is far more powerful than the SimpleXML equivalent:

$dom = new DomDocument(); $dom->load("libra ry.xml");

$xpath->registerNamespace("lib", "http://example.org/library");

$result = $xpath->query("//lib:title/text()");

This example seems quite complex, but in actuality it shows just how flexible the DOM XPath functionality can be.

First, we instantiate a DomXpath object, passing in our DomDocument object so that the former will know what to work on. Next, we register only the namespaces we need, in this case the default namespace, associating it with the lib prefix. Finally, we execute our query and iterate over the results.

A call to DomXpath::query() will return a DomNodeList object; you can find out how many items it contains by using the length property, and then access anyone of them with the item() method. You can also iterate through the entire collection using a foreach()loop:

$result = $xpath->query("//lib:title/text()");

// Random access

echo $book->data;

// Sequential access foreach ($result as $book) { echo $book->data;

0 0

Post a comment

  • Receive news updates via email from this site