Before and After: Searching XML with XPath

Except for the simplest documents, it’s rarely easy to access the data you want one element at a time. As your XML files become increasingly complex and your parsing desires grow, using XPath is easier than filtering the data inside a foreach.

In PHP 4 and PHP 5, there is an XPath class that takes a DOM object as its constructor. You can then search the object and receive DOM nodes in reply. SimpleXML also supports XPath, and it’s easier to use because its integrated into the SimpleXML object.

Whether you’re using XPath with DOM or SimpleXML, both extensions support XML Namespaces. Therefore, you can find elements or attributes that live inside a namespace.

Reading an Address Book

Everything that can be done with the traditional DOM methods can also be done using XPath. The examples in this section also show how to search the address book.

PHP 4 and DOM

To create an XPath query under PHP 4, you must start with a DOM object and pass it off to an XPath context.

Here’s how to retrieve the email addresses of everyone in the address book:

$dom = domxml_open_file('address-book.xml');

$xpath = xpath_new_context($dom);
$emails = $xpath->xpath_eval('/address-book/person/email');

// Can also be:
// $emails = xpath_eval($xpath, '/address-book/person/email');

foreach ($emails->nodeset as $e) {
    $tmp = $e->first_child( );
    $email = $tmp->node_value( );
    // do something with $email

After creating a new DOM object, call xpath_new_context( ) to initialize ...

Get Upgrading to PHP 5 now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.