XPath Is Fun

by Jeffrey R. Crouse

What is XPath?

So you know XML. You've been parsing and syndicating, and generally conquering the web. Good for you. But writing a complicated set of iterators every time you want to get at one piece of information within an XML document is for suckers. With XPath, you can get right at the information you want, and it's as easy as typing in any other kind of path, like in your web browser or Windows Explorer. There are many uses for this, a few of which I will talk about in this tutorial.

Jumping Right In

Lucky for you, PHP has XPath support, and since you all know PHP, you can get your hands dirty right away. Let's start with a simple XML document that describes a breakfast menu. Say this file was published every morning by your favorite restaurant, and you wanted to put this information on your webpage. There are four steps. First just read through, then we'll go back and look at each step in detail.

  1. Create a DomDocument with domxml_open_file().
  2. Make an XPath context with xpath_new_context()
  3. Execute the query with xpath_eval()
  4. Print out the results

Here's some code...

$doc = domxml_open_file('breakfast.xml');
$xpath = $doc->xpath_new_context();
$obj = $xpath->xpath_eval('/breakfast_menu/food/name/text()');
foreach ($obj->nodeset as $node) {
    print "$node->content<br />";
}

And the result is...