XPath Queries

Sep 10, 2009 Author: britney

The XML Path Language (XPath) is a W3C standardized language that is used to access and search XML documents. It is used extensively in Extensible Stylesheet Language Transformations (XSLT) and forms the basis of XML Query (XQuery) and XML Pointer (XPointer). Think of it as a query language for retrieving data from an XML document. XPath can be a very complex language, and with this complexity comes a lot of power, which SimpleXML leverages with the SimpleXMLElement::xpath() method. Using SimpleXMLElement::xpath(), you can run an Xpath query on any SimpleXMLElement object. If used on the root element, it will search the entire XML document. If used on a child, it will search the child and any children it may have. The following illustrates an XPath query on both the root element and a child node. XPath returns an array of SimpleXMLElement objects—even if only a single element is returned.

// Search the root element
$results = $library->xpath(’/library/book/title’);
foreach ($results as $title)
{
echo $title . "\n";
}
// Search the first child element$results = $library->book[0]->xpath(’title’);
foreach ($results as $title)
{
echo $title . "\n";
}

tags: XPath Queries

views 3650
  1. Add New Comment