Getting started
This section shows the smallest useful setup outside of WebEngine.
[!TIP] In WebEngine, you usually do not need this setup code. The framework gives you a pre-constructed
HTMLDocument, and DomTemplate is also available by default if the task is really data binding rather than low-level DOM work.
1. Install the package
composer require phpgt/dom
The package requires PHP’s dom, libxml, and mbstring extensions.
2. Construct an HTMLDocument
use GT\Dom\HTMLDocument;
$html = <<<'HTML'
<!doctype html>
<h1>Hello, <span class="name">you</span>!</h1>
HTML;
$document = new HTMLDocument($html);
At this point we have a document tree we can query and modify using familiar DOM calls.
3. Query the document
$name = $document->querySelector(".name");
$name->innerText = "Cody";
These methods follow the same basic behaviour documented on MDN:
4. Serialise the document
echo $document;
Casting the document to a string serialises it back to markup.
For HTMLDocument, the output always includes a doctype and the root document structure:
<!doctype html>
<html><head></head><body><h1>Hello, <span class="name">Cody</span>!</h1></body></html>
5. Create nodes instead of concatenating HTML when practical
innerHTML and outerHTML are supported, but when we are constructing a few nodes programmatically it is often clearer to use DOM methods directly:
$list = $document->createElement("ul");
foreach(["Tea", "Milk", "Biscuits"] as $item) {
$li = $document->createElement("li");
$li->innerText = $item;
$list->appendChild($li);
}
$document->body->appendChild($list);
MDN references:
6. Keep the right level of abstraction
If you find yourself doing lots of this:
$document->querySelector(".customer-name")->innerText = $customer->name;
$document->querySelector(".customer-email")->innerText = $customer->email;
$document->querySelector(".customer-tier")->innerText = $customer->tier;
it is worth pausing and asking whether the real problem is template binding rather than DOM manipulation. In WebEngine applications especially, DomTemplate is usually the better fit.
Now that we have a document on hand, move on to Parsing documents.