Skip to content
Greg Bowler edited this page Feb 19, 2022 · 4 revisions

Introduction

Both CSS selectors and XPath queries achieve the same goal: obtaining a reference to one or more elements within a document, by using a "locator" string, but CSS selectors are generally simpler than XPath queries, and with their widespread use within web browsers for styling content, CSS selectors are typically understood by a lot more developers.

Some tools, such as PHP's DOMDocument, require the use of XPath queries to traverse the trees of elements. So in order to be able to use CSS selectors within a DOM Document, a CSS selector needs to be translated into an XPath query. This is exactly what PhpGt/CssXPath does.

Comparing CSS selectors with equivalent XPath queries

CSS selectors are often easier to read and write, and are often much more terse compared to XPath queries. This is because an XPath query has much more power and flexibility, but more often than not a CSS selector can achieve the goal of selecting the element(s) the developer needs.

The table below compares some commonly-used CSS selectors with the equivalent XPath queries:

CSS XPath
p .//p
form label>span .//form//label/span
body>header nav li>a .//body/header//nav//li/a
.create-new button[value=submit] .//*[contains(concat(" ",normalize-space(@class)," ")," create-new ")]//button[@value="submit"]
#menu nav[selected] li.highlight .//*[@id="menu"]//nav[@selected]//li[contains(concat(" ",normalize-space(@class)," ")," highlight ")]

Using PhpGt/CssXPath

  1. Use Composer to install CssXPath as a dependency: composer require phpgt/cssxpath.
  2. Include the Gt\CssXPath\Translator class in your code.
  3. Construct a new Translator, passing in the CSS selector as the one and only parameter.
  4. Cast Translator to a string to obtain the XPath query.

Example:

use Gt\CssXPath\Translator;

$translator = new Translator(".create-new button[value=submit]");
echo $translator;

Using with a DOM Document

A common use case for translating a CSS selector to an XPath query is when working with a DOM Document. PHP's native DOMDocument class comes with the DOMXPath functionality, which uses XPath queries to traverse a document. To extend functionality of DOMDocument to something similar to the modern DOM specification, functions querySelector and querySelectorAll can be used to traverse the document using CSS selectors.

This functionality is implemented in PhpGt/Dom to enable the following functionality:

$document = new HTMLDocument($html);
$title = $document->querySelector("body>section header h1");
$title->textContent = "Hello, DOM!";

For more information, see https://www.php.gt/dom