⚠️ This project is no longer maintened. It's recommended to use the DiDOM package as a replacement.
DOM Parser is an elegant and modern HTML / XML parser implemented in PHP with a focus on simplicity.
- Installation
- Usage
- Initializing a new parser
- Searching for element
- Getting element content
- Getting element attributes
- New query from element
- License
You can install the package via composer:
composer require srdante/dom-parserBelow there is a simple example of how to use the package:
use Srdante\DomParser\DomParser;
$htmlContent = '<div>Hello World!</div>';
$query = DomParser::startRelativeQuery($htmlContent);
echo $query->element('div')->first()->getText();You can initialize a new parser class instance using relative query method:
$query = DomParser::startRelativeQuery($htmlContent);Or root query method:
$query = DomParser::startRootQuery($htmlContent);You can do a search for an element and get an array as result:
$parser->element('div', ['id', '=', 'my-header'])->get();Or get the first or last element:
$parser->element('div', ['id', '=', 'my-header'])->first();
$parser->element('div', ['id', '=', 'my-header'])->last();The first parameter is the element tag, and the second (optional) is the "where clause".
There is 3 ways to get the element content. The getText(), getHtml() and getInsideHtml() methods.
getText()returns the element plain-text content.getHtml()returns the element HTML content including the own element.getInsideHtml()returns the element inner HTML content.
$element->getText();
$element->getHtml();
$element->getInsideHtml();You can get all element attributes with the getAttributes() method.
$element->getAttributes()['href'];You can start a new query from any element from the library.
$element->newRootQuery()->element('a')->first();
$element->newRelativeQuery()->element('a')->first();DOM Parser is open-sourced software licensed under the MIT license.