DOM, the built in template system

Posted on 06.06.06

0



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"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>DOM example</title>
  </head>
  <body></body>
</html>

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'));
$link->setAttribute('href','example.css');
$link->setAttribute('type','text/css');
$link->setAttribute('rel','stylesheet');
$body->appendChild($doc->createElement('h1','Contents'));

// Printing the modified document...
print($doc->saveXML());

Suggested readings

Advertisements
Tagged: , , ,
Posted in: Uncategorized