devanoxltd/php-html-parser
Lightweight PHP HTML parser with jQuery-style CSS selectors. Load HTML from strings or files, handle imperfect markup, and traverse nodes (attributes, innerHtml, siblings). Ideal for quick web scraping and DOM extraction in PHP 7.2–7.4.
## Getting Started
Install via Composer:
```bash
composer require paquettg/php-html-parser
The package provides a fluent API for parsing, manipulating, and generating HTML. Start with the Parser class for parsing HTML strings:
use Paquettg\HtmlParser\Parser;
$html = '<div class="example"><p>Hello <strong>World</strong></p></div>';
$dom = Parser::parse($html);
// Access nodes via DOM traversal
$div = $dom->getElementByTagName('div')->first();
$strong = $div->getElementByTagName('strong')->first();
$strong->setName('em'); // New in 1.2.0: Use setName() instead of deprecated methods
echo $div->saveHtml();
Key first-use cases:
Parsing and Querying:
$parser = new Parser();
$dom = $parser->parse('<div id="content">...</div>');
$nodes = $dom->getElementById('content');
Attribute Manipulation:
$node->setAttribute('class', 'updated');
$node->removeAttribute('data-old');
Text Extraction:
$text = $node->getText(); // Get all text content
$cleanText = $node->getInnerText(); // New in 1.2.0: Fixed null handling
Encoding Handling (New in 1.2.0):
use Paquettg\HtmlParser\Encoder\HtmlEntityEncoder;
$encoder = new HtmlEntityEncoder();
$node->setEncoder($encoder); // Custom encoding via EncoderInterface
@php
$html = Parser::parse($rawHtml)->saveHtml();
@endphp
{!! $html !!}
$cleanHtml = Parser::parse($userInput)->saveHtml();
Parser for unit tests:
$this->partialMock(Parser::class, ['parse']);
$node->tag). Use:
$node->getTag(); // Preferred in 1.2.0
$node->setName('span'); // New method for tag name changes
mb_ereg_replace fixes in TextNode may affect edge cases with multibyte strings. Test with non-ASCII content.saveHtml() to inspect modified DOM:
echo $node->saveHtml(); // Debug rendered output
$node->setEncoder(new HtmlEntityEncoder());
EncoderInterface for custom HTML encoding:
class MyEncoder implements EncoderInterface {
public function encode($text) { ... }
}
Parser for pre/post-processing:
$parser = new Parser();
$parser->on('parse', function($dom) { /* Modify DOM */ });
$dom->getElementByTagName('a')
->each(function($node) { $node->setAttribute('rel', 'nofollow'); });
NO_UPDATE_NEEDED would **not** apply here due to the new features (e.g., `setName()`, `EncoderInterface`) and breaking changes. The above is the updated assessment.
How can I help you explore Laravel packages today?