Cesar
Cesar

Reputation: 534

How to capture HTML for a PHP variable

I have dozens of templates elaborated by a web designer. They are primarily HTML, with a few PHP tags and data. The problem is that I need to re-use those templates (tpl.php) to send email, and the email body (through PHPMailer) is a variable. I have succeeded to fill a variable with the HTML output in the code example (adapted). My question is: should I redo all the templates or is this a valid approach?

<?php
  print "This will print just the 'hello world' output. I don't need to print the function as it has no return value<br />";

 hola_mundo(); // I directly call the function and it outputs HTML to the screen
 print "<br />";
 // Now the assignment to the variable.
 ob_start(); // I silence the output to screen
 hola_mundo();
 $string = ob_get_contents(); // I capture the buffer
 ob_end_clean(); // I restore the output to screen

 print "Now I print the string variable to demonstrate it has captured the HTML ";
 print $string;

function hola_mundo(){
   ?><font color="red"<b>HOLA MUNDO CRUEL</b></font><?php
} // function



?>

The more logical approach would be to have this function (which I do not have and should redo for dozens of templates):

<?php
   $string = hola_mundo();
   print $string;


   function hola_mundo(){
   $string = '<font color="red"<b>HOLA MUNDO CRUEL</b></font>';
   return $string
 } // function

 ?>

Upvotes: 1

Views: 1014

Answers (1)

Pieter van den Ham
Pieter van den Ham

Reputation: 4494

Do you mean this?

function getTemplate($file) {
    ob_start();
    include $file;
    return ob_get_clean();
}

// Example usage:
$string = getTemplate('templates/tpl.php');

tpl.php will be executed as a PHP file.

You can even pass variables to the template:

function getTemplate($file, $variables=array()) {
    extract($variables);
    ob_start();
    include $file;
    return ob_get_clean();
}

// Example usage:
$string = getTemplate('templates/tpl.php', array('message' => 'Hello world!'));

This will extract 'Hello world' into the function scope, making it available as the $message variable to the template.

Upvotes: 2

Related Questions