DOM, the built in template system

Posted on 06.06.06


It’s allways good to separate code and markup, and with DOM you can do such a thing. We will look at these properties of DOM in this article:

  1. Load and parse a base XHTML file
  2. Fetch elements using XPath
  3. Append some XHTML elements
  4. Print the modified document

Let’s start with the file base.xml:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    <title>DOM example</title>

Tip: To get Iternet Explorer 6 into “almost strict mode” the XML declaration needs to be removed. If not IE will turn into “quirks mode”.

Next step is to load the XML and add a style sheet and some contents. After the document has been created we fetch the head and body tag. Finally we modify the document and print it.

// Creating and parsing the base.xml document...
$doc = DOMDocument::load('base.xml');

// Instantiating XPath object...
$xp = new DOMXPath($doc);

// Fetching elements...
$head = $xp->query('/html/head')->item(0);
$body = $xp->query('/html/body')->item(0);

// Appending contents...
$link = $head->appendChild($doc->createElement('link'));

// Printing the modified document...

Suggested readings

Tagged: , , ,
Posted in: Uncategorized