Rct567 / DomQuery

PHP library for easy 'jQuery like' DOM traversing and manipulation.
MIT License
131 stars 38 forks source link
dom domdocument domquery html htmlparser jquery libxml php-library xpath xpath-query

DomQuery

DomQuery is a PHP library that allows you to easily traverse and modify the DOM (HTML/XML). As a library it aims to provide 'jQuery like' access to the PHP DOMDocument class (http://php.net/manual/en/book.dom.php).

Installation

Install the latest version with

$ composer require rct567/dom-query

Basic Usage

Read attributes and properties:

use Rct567\DomQuery\DomQuery;

$dom = new DomQuery('<div><h1 class="title">Hello</h1></div>');

echo $dom->find('h1')->text(); // output: Hello
echo $dom->find('div')->prop('outerHTML'); // output: <div><h1 class="title">Hello</h1></div>
echo $dom->find('div')->html(); // output: <h1 class="title">Hello</h1>
echo $dom->find('div > h1')->class; // output: title
echo $dom->find('div > h1')->attr('class'); // output: title
echo $dom->find('div > h1')->prop('tagName'); // output: h1
echo $dom->find('div')->children('h1')->prop('tagName'); // output: h1
echo (string) $dom->find('div > h1'); // output: <h1 class="title">Hello</h1>
echo count($dom->find('div, h1')); // output: 2

Traversing nodes (result set):

use Rct567\DomQuery\DomQuery;

$dom = new DomQuery('<a>1</a> <a>2</a> <a>3</a>');
$links = $dom->children('a');

foreach($links as $elm) {
    echo $elm->text(); // output 123
}

echo $links[0]->text(); // output 1
echo $links->last()->text(); // output 3
echo $links->first()->next()->text(); // output 2
echo $links->last()->prev()->text(); // output 2
echo $links->get(0)->textContent; // output 1
echo $links->get(-1)->textContent; // output 3

Factory method (create instance alternative):

use Rct567\DomQuery\DomQuery;

DomQuery::create('<a title="hello"></a>')->attr('title') // hello

Jquery methods available

Traversing > Tree Traversal

Traversing > Miscellaneous Traversing

* [selector] can be a css selector or an instance of DomQuery|DOMNodeList|DOMNode

Manipulation > DOM Insertion & removal

* [content] can be html or an instance of DomQuery|DOMNodeList|DOMNode

Attributes | Manipulation

* addClass, removeClass, toggleClass and removeAttr also accepts an array or space-separated names

Miscellaneous > DOM Element Methods | Traversing | Storage

Supported selectors

Pseudo selectors

Other (non jQuery) methods

XML support

Escaping meta chars in selector to find elements with namespace:

$dom->find('namespace\\:h1')->text();

About

Requirements

Inspiration/acknowledgements