-
-
Notifications
You must be signed in to change notification settings - Fork 28
Home
The Document Object Model (DOM) is an object-oriented interface for interacting with HTML webpages and other XML documents. It's been made extremely popular by its use in JavaScript within the browser.
The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree. With them, you can change the document's structure, style, or content.
This project provides access to a DOM within your PHP scripts on the server, for use with HTML or XML Documents, allowing developers to take advantage of the well known web standards and widely understood DOM technologies to produce dynamic pages alongside, or instead of, a template engine.
This documentation does not try to re-document the whole browser DOM API. MDN already does that very well. Here we will focus on the parts that matter when using DOM on the server:
- how to construct documents and parse markup
- how the live collections behave
- where the implementation intentionally differs from the browser
- how to fit the library into WebEngine applications
- when DomTemplate is a better choice than manual DOM manipulation
Important
If you are building with WebEngine, you usually do not construct HTMLDocument yourself. WebEngine provides a pre-constructed HTML document for the page request.
Within WebEngine applications, DomTemplate is also shipped by default, so it is worth understanding what that library already does before reaching for manual DOM manipulation.
In many cases, binding data with DomTemplate is the cleaner option because it keeps PHP logic and HTML structure more loosely coupled.
-
HTMLDocumentandXMLDocumentwrappers around PHP's native DOM classes. - Modern selector-based traversal with
querySelector()andquerySelectorAll(). - Browser-style helpers such as
classList,dataset,closest(),before(),after(),replaceWith(),innerHTML, andouterHTML. - Live
HTMLCollectionand live/staticNodeListbehaviour where the standard expects it. - A large amount of element-specific IDL behaviour for forms, tables, media elements, and other HTML interfaces.
- Explicit exceptions when functionality only makes sense in the browser.
use GT\Dom\HTMLDocument;
$html = <<<HTML
<!doctype html>
<h1>Hello, <span class="name">you</span>!</h1>
HTML;
$document = new HTMLDocument($html);
$document->querySelector(".name")->innerText = "Cody";
echo $document;Output:
<!doctype html>
<html><head></head><body><h1>Hello, <span class="name">Cody</span>!</h1></body></html>The code feels very similar to browser DOM code, but it runs entirely on the server.
To see where this library fits in, continue to Overview.
PHP.GT/Dom is a separately maintained component of PHP.GT/WebEngine.