So, I have a template engine I made and I want to replace {pageBody} with contents from a PHP file, when I do it using the template engine it does not execute the PHP, rather it displays it in view source option.
TEMPLATE.PHP
<?php
class TemplateLibrary {
public $output;
public $file;
public $values = array();
public function __construct($file) {
$this->file = $file;
$this->file .= '.tpl';
$this->output = file_get_contents('templates/'.$this->file);
}
public function replace($key, $value)
{
$this->values[$key] = $value;
}
public function output() {
foreach($this->values as $key => $value)
{
$ttr = "{$key}";
$this->output = str_replace($ttr, $value, $this->output);
}
return $this->output;
}
}
index.tpl
<!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=iso-8859-1" />
<title>{page_title}</title>
{page_style}
</head>
<body>
{page_header}
{page_body}
{page_footer}
</body>
</html>
HTML replace works fine, but PHP does not. Any ideas?
You are rather scattered with your files and the list is incomplete. I’ve listed all the files you’ve provided so far below.
@Jonathon above is correct, that you will need to use output buffering to capture the output of the PHP file and
include()the file (so it gets executed) instead of usingfile_get_contents()(which does not execute the file).[edit] I re-created all these files in my local environment and confirmed that @Jonathon’s suggestion worked perfectly. I’ve updated dev/replacements.php to include the suggested code.
Additionally, I added two more functions to your
TemplateLibraryclass :replaceFile($key, $filename)that does thefile_get_contents($filename)so that you don’t have to repeat it so often, andreplacePhp($key, $filename)that performs aninclude()while capturing the output, so you can encapsulate the complexities of including a PHP file.Good Luck!
main.php
dev/templatelibrary.php
index.tpl
replacements.php
loaders/pageBody.php
[edit] added loaders/pageBody.php from OP’s comment.
[edit] Updated dev/replacements.php to capture output buffer and use include on .php