Essentially, the script I am about to explain to you is to allow you to include one template file to your script then change parts of it dynamically before outputting it to the visitors browser. Right now I'm using it to include an xhtml file, then change the title, body, and stylesheet link as necessary.
The first thing you are going to need for this method is the template for your pages. As I said before, I'm using an xhtml file, which right now contains this:
Code: Select all
<?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 xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="{style}" />
<title>{title}</title>
</head>
<body>
{body}
</body>
</html>
Code: Select all
<?php
class OutputHandler {
public $Page;
public function __construct ($Template) {
if (file_exists($Template)) {
$this->Page = file_get_contents($Template);
} else {
die ('No template could be found.');
}
}
public function ReplaceTags ($Tags) {
foreach ($Tags as $Tag => $Data) {
$this->Page = str_replace("{" . $Tag . "}", $Data, $this->Page);
}
}
public function OutputHTML () {
echo $this->Page;
}
}
?>
Now the second function in our output handler is where the actual processing happens. It takes the argument '$Tags' which is an array containing all the tags we want to change as the key, and the value we are going to change them to as the value.
A for each loop goes through this array, and changes $Page (which contains all our html) so instead of containing "{body}" and "{title}" it now contains whatever we want it to in their place.
Finally, we need to make our main page to test this out. Here is my index.php:
Code: Select all
require ('Classes/OutputHandler.php');
$Body = '<h2>My website</h2>
<hr />
<p>This is my website. Do do do..</p>';
$OutputHandler = new OutputHandler ('Template/Template.xhtml');
$OutputHandler->ReplaceTags(array (
'style' => 'Styles/Style.css',
'title' => 'This is the title of my page',
'body' => $Body
));
$OutputHandler->OutputHTML();
?>
Then I call "OutputHTML()" to send the result to the browser.

So I hope I went through this thoroughly enough. In it's current state I'm sure there are a few problems somewhere in this script, but it does work, and can be pretty handy. I found something similar to this on the internet earlier today when I was looking for ways to keep HTML in my PHP scripts cleaner and easier to read. Im sure it's a lot slower because we are using PHP to output all our html, but still.. It was an interesting find.
Thanks for reading this rather long and time consuming post.
