Introduction to XPath
An introduction to XPath, what it is used for, and how to run XPath queries with PHP.
XPath, short for XML Path Language, is a query language for selecting nodes in an XML document. It has been around since 1999 and is commonly used to navigate XML structures.
The standard is maintained by the W3C, and you can review the details in the W3C XPath specification.
XPath is also used together with technologies such as XPointer, XSLT, and other XML-related standards.
I recommend reviewing Introduction to XML to learn concepts such as root element, child element, etc. when writing XPath.
We will continue with the library.xml file used in the previous examples. As a reminder:
<books>
<book isbn="9759954949">
<title>Yunus Emre Divani</title>
<author role="Editor">Selim Yagmur</author>
<language>Turkish</language>
<edition>8</edition>
<date>
<year>2014</year>
<month>04</month>
<day>01</day>
</date>
</book>
<book isbn="9753386203">
<title>Risaletun-Nushiyye Yunus Emre</title>
<author role="Translator">Prof. Dr. Umay Turkes Gunay</author>
<language>Turkish</language>
<edition>3</edition>
<date>
<year>2009</year>
<month>01</month>
<day>01</day>
</date>
</book>
</books>
Now let's query the book elements from the XML and list only their titles.
<?php
$xml = simplexml_load_file("library.xml"); // we load the library into a variable
$results = $xml->xpath('book'); // we assign all book elements to the results variable.
foreach ($results as $key => $value) {
echo $value->title; // we print the value of the title element under each book.
}
?>
// Screen Output
Yunus Emre Divani
Risaletun-Nushiyye Yunus Emre
When we use xpath('element'), XPath returns the matching elements. In the next example, we use xpath('/element'), which is a full-path query. That means the path must be written from the root element to the target element.
<?php
$xml = simplexml_load_file("library.xml"); // we load the library into a variable
$results = $xml->xpath('/books/book'); // we assign all book elements under the books root to the results variable.
foreach ($results as $key => $value) {
echo $value->title; // we print the value of the title element under each book.
}
?>
// Screen Output
Yunus Emre Divani
Risaletun-Nushiyye Yunus Emre
As you can see, the result is the same.