O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required