XPath queries in PHP

XPath is a query language for selecting XML nodes. Suppose that you have a collection of companies represented in an XML document.

<?xml version="1.0" encoding="utf-8"?>
<companies>
  <company>
    <name>Apple</name>
    <ceo>Steve Jobs</ceo>
  </company>
  <company>
    <name>Microsoft</name>
    <ceo>Steve Ballmer</ceo>
  </company>
  <company>
    <name>Google</name>
    <ceo>Larry Page</ceo>
  </company>
  <company>
    <name>Intel</name>
    <ceo>Paul S. Otellini</ceo>
  </company>
</companies>

The XPath query to select Google is illustrated below.

/companies/company[name='Google']

PHP5 supports the DOMXPath class for executing XPath queries for DOM trees. This is illustrated below.

<?php

    $xmlDocument = new DOMDocument();

    // Load the XML document
    $xmlDocument->load('companies.xml');

    $xPath = new DOMXPath($xmlDocument);

    // Define the XPath query to select Google
    $xPathQuery = "/companies/company[name='Google']";

    // Execute the query
    $queryNodes = $xPath->query($xPathQuery);

    // Iterate through the results
    foreach($queryNodes as $companyNode){
        // Print the node name
        print $companyNode->nodeName."\n";
        foreach($companyNode->childNodes as $companyChildNode){
            // Only print element nodes
            if($companyChildNode->nodeType == XML_ELEMENT_NODE){
                // Print the node name and value
                print $companyChildNode->nodeName .
                        ": ".$companyChildNode->nodeValue."\n";
            }
        }
    }

?>

Output:

company
name: Google
ceo: Larry Page
This entry was posted in PHP and tagged , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?