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"?>
    <ceo>Steve Jobs</ceo>
    <ceo>Steve Ballmer</ceo>
    <ceo>Larry Page</ceo>
    <ceo>Paul S. Otellini</ceo>

The XPath query to select Google is illustrated below.


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


    $xmlDocument = new DOMDocument();

    // Load the XML document

    $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";



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?