Using with DOMDocument
Using with DOMDocument
The common workflow is to load markup into DOMDocument, create DOMXPath, and pass a Translator instance into query().
use DOMDocument;
use DOMXPath;
use Gt\CssXPath\Translator;
$document = new DOMDocument();
$document->loadHTMLFile("index.html");
$xpath = new DOMXPath($document);
$result = $xpath->query(new Translator("main article p"));
foreach($result as $p) {
echo trim($p->textContent) . PHP_EOL;
}
Selecting relative to a node
DOMXPath::query() supports a context node. Here we can keep one translator and query different branches of the same document:
$allItems = $xpath->query(new Translator("li"));
$itemsInNav = $xpath->query(
new Translator("li"),
$document->getElementsByTagName("nav")->item(0)
);
Grouped selectors
Comma-separated CSS selectors are translated to XPath expressions joined by |.
echo new Translator("h1, p");
// .//h1 | .//p
This lets us fetch mixed sets of nodes using a single query.
Next up, we’ll learn the selector syntax.