XPath in PHP
XPath is a query language for selecting XML nodes. Both SimpleXML and DOMDocument support XPath via their xpath() and evaluate() methods.
XPath is a query language for selecting XML nodes. Both SimpleXML and DOMDocument support XPath via their xpath() and evaluate() methods.
<?php
$xml = simplexml_load_string($xmlData);
// Select all user elements
$users = $xml->xpath("//user");
// Select users with a specific attribute
$admins = $xml->xpath("//user[@role='admin']");
// Select text content of a specific node
$names = $xml->xpath("//user/name/text()");
// DOMDocument + XPath
$dom = new DOMDocument();
$dom->loadXML($xmlData);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//user[@active='1']/email");
foreach ($nodes as $node) {
echo $node->textContent . "
";
}
XPath is far more powerful than manual XML traversal — use it for complex selections and filtering by attribute values.