Installation:
composer require phpgt/dom
No additional configuration is required—just autoload via Composer.
First Use Case: Parse and manipulate HTML/XML with a modern, chainable API:
use Phpgt\Dom\Document;
$html = '<div class="container"><h1>Hello</h1><p>World</p></div>';
$dom = Document::loadHtml($html);
// Query and modify
$dom->query('h1')->setText('Updated Title');
echo $dom->saveHtml();
Key Entry Points:
Document::loadHtml() / Document::loadXml() – Parse strings or files.$dom->query() – Select elements (CSS selectors or XPath).$element->setAttribute() / $element->remove() – Modify structure/content.Scraping & Data Extraction:
$dom = Document::loadHtml(file_get_contents('https://example.com'));
$titles = $dom->query('article h2')->map(fn($el) => $el->textContent);
Dynamic HTML Generation:
$dom = new Document();
$dom->appendChild($dom->createElement('div'))
->setAttribute('id', 'dynamic-content')
->appendChild($dom->createTextNode('Dynamic!'));
Integration with Laravel:
Document to pre-process HTML before rendering:
$dom = Document::loadHtml(view('partials.header')->render());
$dom->query('.logo')->setAttribute('src', asset('new-logo.png'));
echo $dom->saveHtml();
$cleaned = Document::loadHtml($request->input('html_content'))
->query('script')->remove()
->saveHtml();
Testing:
$this->assertEquals(
'<div>Test</div>',
Document::loadHtml('<div>Test</div>')->saveHtml()
);
$dom->query('.item')->each(fn($el) => $el->setAttribute('data-id', $el->id));
XPath vs. CSS Selectors:
query('div > p')) are faster but less powerful than XPath.query('//div[@class="nested"]//a')).Namespace Handling:
$dom = Document::loadXml('<svg xmlns="http://www.w3.org/2000/svg">...</svg>');
$dom->registerNamespace('svg', 'http://www.w3.org/2000/svg');
$dom->query('svg|circle')->remove();
HTML5 Quirks:
<img />) may render differently in saveHtml(). Use:
$dom->setFormatOutput(true); // Pretty-print with proper tag closing.
Memory Usage:
DOMDocument::loadHTMLFile() (native) as a fallback.$dom->query('body')->each(fn($el) => dump($el->outerHTML));
$dom->validate(); // Throws exception on malformed XML.
Custom Elements:
Extend Phpgt\Dom\Element for domain-specific methods:
class ArticleElement extends Element {
public function getTitle(): string {
return $this->query('h1')->textContent;
}
}
Event Listeners: Hook into DOM events (e.g., post-load) via traits or decorators.
Integration with Guzzle: Combine with HTTP clients for headless scraping:
$html = $client->request('GET', $url)->getBody();
$dom = Document::loadHtml($html);
Document::loadHtml() auto-detects HTML5; force a doctype with:
$dom = new Document();
$dom->appendChild($dom->createProcessingInstruction('xml', 'version="1.0"'));
How can I help you explore Laravel packages today?