Example 6: XPath Queries
Search for and select specific nodes within an XML document
🎯 What does this example cover?
XPath es un lenguaje de rutas para "preguntarle" a un documento XML por nodos concretos, igual que una ruta de carpetas señala un archivo. Este ejemplo ejecuta, de verdad, la expresión que escribas contra el documento de muestra (una biblioteca de 4 libros) usando SimpleXMLElement::xpath(), y te muestra los nodos encontrados.
Write an XPath expression
<?xml version="1.0" encoding="UTF-8"?>
<biblioteca>
<libro id="001" genero="Novela">
<titulo>El Quijote</titulo>
<autor>Miguel de Cervantes</autor>
<anio>1605</anio>
</libro>
<libro id="002" genero="Realismo magico">
<titulo>Cien anios de soledad</titulo>
<autor>Gabriel Garcia Marquez</autor>
<anio>1967</anio>
</libro>
<libro id="003" genero="Novela">
<titulo>Orgullo y prejuicio</titulo>
<autor>Jane Austen</autor>
<anio>1813</anio>
</libro>
<libro id="004" genero="Gotica">
<titulo>Dracula</titulo>
<autor>Bram Stoker</autor>
<anio>1897</anio>
</libro>
</biblioteca>
Query result
El Quijote --- Cien anios de soledad --- Orgullo y prejuicio --- Dracula
📖 Code Explanation
Complete PHP Code
<?php
$dom = new DOMDocument();
$dom->loadXML($xmlBiblioteca);
$xpath = new DOMXPath($dom);
$resultado = $xpath->evaluate('/biblioteca/libro/titulo');
foreach ($resultado as $nodo) {
echo $nodo->textContent, "\n";
}
?>
📝 Load the document and create the query engine
$xpath = new DOMXPath($dom);
What does it do? Loads the XML into a DOMDocument and creates a DOMXPath object associated with it, which is what knows how to run XPath expressions on that document.
📝 Run the query
What does it do? Returns the nodes that match the given path, or a scalar value (number, text or boolean) if the expression is of the count(...) type. /biblioteca/libro/titulo reads as "from the root, go into biblioteca, then into each libro, and take its titulo".
💡 Concept: paths, filters and functions
// searches at any level, brackets [...] filter by condition (for example [@genero='Novela'] by attribute, or [anio > 1900] by a child's value), and functions like count() return a number instead of nodes.
🎯 Key Concepts Learned
Path Syntax
/absolute path from the root//searches at any level@atributoselects attributes
Filters with Brackets
[@id='003']filters by attribute[anio > 1900]filters by value[contains(texto, 'x')]searches for substrings
DOMXPath in PHP
evaluate()accepts nodes and scalarsquery()always returns nodes- Returns
falseif the expression is invalid
💪 Practical Exercise
Master your own queries
- Use the quick buttons and observe how the result changes in each case
- Write an expression that returns only the author of the book with
id="002" - Write an expression that returns books published before 1900
- Try writing an expression with an unclosed bracket and observe the error message
Author of the book with id="002"
/biblioteca/libro[@id='002']/autor
Books before 1900
/biblioteca/libro[anio < 1900]/titulo