bdk/css-xpath

Search html via CSS selector or convert css selector to xpath

Maintainers

👁 brad.kent

Package info

github.com/bkdotcom/CssXpath

Homepage

pkg:composer/bdk/css-xpath

Statistics

Installs: 32 235

Dependents: 3

Suggesters: 0

Stars: 9

Open Issues: 0

v1.0.2 2025-11-17 21:10 UTC

Requires

  • php: >=5.3.0

Requires (Dev)

Suggests

None

Provides

None

Conflicts

None

Replaces

None

MIT e5bf246e80f9f20667322230f56e3b26e37d1183

cssXpath

This package is auto-updated.

Last update: 2026-06-17 22:34:16 UTC


README

  • Convert CSS selector to XPath
  • Query HTML string (or \DOMDocument) by CSS selector
  • Provide PHPUnit Assertions (once provided by PHPUnit)

👁 No Dependencies
👁 Supported PHP versions
👁 Build Status

Installation

composer require bdk/css-xpath

Usage

CSS to XPath

\bdk\CssXpath\CssXpath::cssToXpath('ul > li:first-child');	// returns '//ul/li[1]'

Query DOM/HTML

Example:

$html = <<<HTML
<div id="article" class="block large">
 <h2>Article Name</h2>
 <p>Contents of article</p>
 <ul>
 <li>One</li>
 <li>Two</li>
 <li>Three</li>
 <li>Four</li>
 <li><a href="#">Five</a></li>
 </ul>
</div>
HTML;

// use static method
var_dump(\bdk\CssXpath\CssSelect::select($html, 'ul > li:last-child [href]'));

// or create and use an instance
$cssSelect = new \bdk\CssXpath\CssSelect($html);
$found = $cssSelect->select('ul > li:last-child [href]');

Output:

array (size=1)
 0 =>
 array (size=3)
 'name' => string 'a' (length=1)
 'attributes' =>
 array (size=1)
 'href' => string '#' (length=1)
 'innerHTML' => string 'Five' (length=4)

Pass a last argument of true, to return a \DOMNodeList object instead of an array

PHPUnit

bdk\CssXpath\DOMTestCase extends \PHPUnit\Framework\TestCase and provides 3 assertions:

  • assertSelectCount($selector, $count, $actual, $message = '')
  • assertSelectRegExp($selector, $pattern, $count, $actual, $message = '')
  • assertSelectEquals($selector, $content, $count, $actual, $message = '')

These assertions were originally provided with PHPUnit 3.3, but removed with PHPUnit 5.0