Page 1 of 1

How to modify templates using DOMDocument in php

Posted: Mon Mar 01, 2010 12:06 am
by Neo
In the previous post, Generating (X)HTML Documents Using DOMDocument In PHP, we explored the PHP DOMDocument class by generating an (X)HTML page completely within PHP. Now, we'll look at a more practical application that involves modifying an existing template. The template gives us a good starting point so we can focus on generating only the dynamic parts of the page.

So here is the template we will be modifying. It is identical to the page we generated, except that the title and content are removed. We will insert a title and content with PHP.

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
  <div id="header"><img src="header.gif" alt="Header" width="400" height="100" /></div>
  <div id="nav">
    <ul>
      <li><a href="index.php">Home</a></li>
      <li><a href="download.php">Download</a></li>
      <li><a href="features.php">Features</a></li>
      <li><a href="about.php">About</a></li>
    </ul>
  </div>
  <div id="content"></div>
</div>
</body>
</html> 

Now for the code. First, we need to load the template document, called template.htm, with the DOMDocument::loadHTMLFile method.

Code: Select all

<?php
// Load the template file into a new DOMDocument
$document = new DOMDocument();
$document->loadHTMLFile('template.htm'); 

Here we create the title text and insert it into the title tag. We grab the first "title" element and append the text node.

Code: Select all

// Set the page title
$title = $document->createTextNode('Page Title');
$document->getElementsByTagName('title')->item(0)->appendChild($title); 
Find the "content" div so we can add our content:

Code: Select all

// Access the content div
$content = $document->getElementById('content'); 
Here is where we generate the content:

Code: Select all

// Insert actual page content into content div
$h1 = $document->createElement('h1', 'DOMDocument Template');
$content->appendChild($h1);
 
$p = $document->createElement('p');
$text = $document->createTextNode('This template was modified using PHP\'s ');
$p->appendChild($text);
$text = $document->createElement('strong', 'DOMDocument');
$p->appendChild($text);
$text = $document->createTextNode(' class!');
$p->appendChild($text);
$content->appendChild($p); 
Now we output the modified document:

Code: Select all

// Output document
$document->formatOutput = true;
echo $document->saveXML();