Query DOM Elements With PHP and CSS Selectors

Ever wanted to select DOM elements using PHP and CSS selectors similar to jQuery? well now you can! Currently most CSS3 selectors are supported.

PHP Selector Source

Located at Github.

CSS Selector Examples

Given the following sample html:

$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;

The function invocations below will all return elements:

  select_elements('div#article.large', $html);
  select_elements('div > h2:contains(Article)', $html);
  select_elements('div p + ul', $html);
  select_elements('ul > li:first-child', $html);
  select_elements('ul > li ~ li', $html);
  select_elements('ul > li:last-child', $html);
  select_elements('li a[href=#]', $html);

Alternatively you may use the SelectorDOM class for persistence:

  $dom = new SelectorDOM($html);
  $dom->select('div#article');
  $dom->select('div > h2:contains(Article)');
  $links = $dom->select('ul li:last-child a');
  // $links[0]['attributes']['href']  ->  #
  ...

More Information

For more information view the source code