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);
Code: Select all
// Access the content div
$content = $document->getElementById('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);
Code: Select all
// Output document
$document->formatOutput = true;
echo $document->saveXML();