I\'m messing around with templating and I\'ve run into a situation where I need to echo to the browser a template that contains html & php. How do I evaluate the PHP and
$contents = htmlentities($contents);
echo html_entity_decode(eval($contents));
In case you are trying to do this with a string of mixed HTML/PHP (like from a database, as I was), you can do it this way:
eval(' ?>'.$htmlandphp.'<?php ');
More info: http://blog.5ubliminal.com/posts/eval-for-inline-php-inside-html/ (note this is a dead link as of 2014-3-3)
The best solution in your case is to combine eval
and output buffer
// read template into $contents
// replace {title} etc. in $contents
$contents = str_replace("{title}", $title, $contents);
ob_start();
eval(" ?>".$contents."<?php ");
$html .= ob_get_clean();
echo html;
Do not read the file, but include it and use output bufferig to capture the outcome.
ob_start();
include 'main.php';
$content = ob_get_clean();
// process/modify/echo $content ...
Edit
Use a function to generate a new variable scope.
function render($script, array $vars = array())
{
extract($vars);
ob_start();
include $script;
return ob_get_clean();
}
$test = 'one';
echo render('foo.php', array('test' => 'two'));
echo $test; // is still 'one' ... render() has its own scope
Use output buffering instead. eval()
is notoriously slow.
main.php:
<div id="container">
<div id="title"><?php echo $title; ?></div><!-- you must use PHP tags so the buffer knows to parse it as such -->
<div id="head">
<?php if ($id > 10): ?>
<H3>Greater than 10!</H3>
<?php else: ?>
<H3>Less than 10!</H3>
<?php endif ?>
</div>
</div>
Your file:
$title = 'Lorem Ipsum';
$id = 11;
ob_start();
require_once('main.php');
$contents = ob_get_contents();
ob_end_clean();
echo $contents;
The output of this will be:
Lorem Ipsum
Greater than 10!