Skip to content

Using DOM in PHP

Greg Bowler edited this page Jun 12, 2017 · 17 revisions

The easiest way to use DOM in your PHP application is to install it as a dependency via Composer.

From your project's root directory, assuming you have Composer installed:

composer require phpgt/dom

Composer will download and install DOM and its dependencies into your project within the vendor/ directory. Inside that directory is the Composer autoloader script, which can be used to magically load any class you have installed.

Once DOM is installed using Composer:

<?php
require "vendor/autoloader.php";
$document = new Gt\Dom\HTMLDocument("<!doctype html><h1>Hello, World!</h1>");
$h2 = $document->createElement("h2");
$h2->textContent = "Goodbye, World!";
$document->body->appendChild($h2);

echo $document->saveHTML();

Without Composer

All releases are available on Github in zip and tar format for downloading. Of course you can clone the git repository too. This library follows the PSR-4 standard for autoloading, so once you have this library's PHP scripts in your project you can use a simple autoloader function to load the classes as they are referenced in your code.

Loading and rendering a page

A webpage's lifespan begins with an HTTP request from a browser to a server. After the server processes the page in some way, a corresponding HTTP response is sent back to the browser. For example, a request might be to get /quote-of-the-day and a corresponding response might be <!doctype html><h1>Quote of the day</h1><p id="output">Don't waste your time, or time will waste you.</p>. Building the response using code is where DOM comes in to make things easier.

The DOM is an indispensable tool when working with webpages, but to get the most out of it will require some code to route the incoming request to your code in a structured way. See the following sections for trivial examples of how to do this.

Loading HTML into a new DOM

// TODO: file_get_contents

Rendering DOM contents to the browser

// TODO: echo (string)$document;

Routing requests

// TODO: file_get_contents("page/$uri");

Separating logic

// TODO: executing page logic PHP in context of page view. Note WebEngine here.