-
-
Notifications
You must be signed in to change notification settings - Fork 28
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.
composer require phpgt/domThe package requires PHP's dom, libxml, and mbstring extensions.
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.
$name = $document->querySelector(".name");
$name->innerText = "Cody";These methods follow the same basic behaviour documented on MDN:
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>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:
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.
PHP.GT/Dom is a separately maintained component of PHP.GT/WebEngine.