Rendering PHP Template To String
August 05, 2008In my current project at home I had need to build a plain text report (for an email) which will be temporarily saved in a database in its final form.
Naturally I wanted to use PHP5 to generate the report layout since it is after all a templating system. It turns out to be quite easy to do.
// define data here, referenced in the report
if(ob_start())
{
include_once 'inc/registrationreport.php';
$str=ob_get_contents();
ob_end_clean();
}
// in in the report, lines like:
Name: <?= $reg_firstname ?> <?= $reg_lastname ?>
Birthdate: <?= $reg_birthdate ?>
Easy as pie. The only odd thing was making sure I wound up with the right linebreaks I had to add blank lines after the data references. You also have to make sure that the ob_end_clean() is properly balanced with the ob_start() or interesting things begin to happen.
Yes, I know that the short form is deprecated.