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> A�A�<company> A�A�A�A�<name>Apple</name> A�A�A�A�<ceo>Steve Jobs</ceo> A�A�</company> A�A�<company> A�A�A�A�<name>Microsoft</name> A�A�A�A�<ceo>Steve Ballmer</ceo> A�A�</company> A�A�<company> A�A�A�A�<name>Google</name> A�A�A�A�<ceo>Larry Page</ceo> A�A�</company> A�A�<company> A�A�A�A�<name>Intel</name> A�A�A�A�<ceo>Paul S. Otellini</ceo> A�A�</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