danb danb - 1 year ago 76
PHP Question

Can you render a PHP file into a variable?

If I have a hello.php file like this:

Hello, <?php echo $foo; ?>!

I would like to do something like this in some php code:

$text = renderPhpToString('hello.php', array('foo'=>'World'));

and end up with

$text == 'Hello, World!'

Is this possible with standard PHP 5? Obviously I want more complex templates with loops and so forth..

Answer Source

You could use some function like this:

function renderPhpToString($file, $vars=null)
    if (is_array($vars) && !empty($vars)) {
    include $file;
    return ob_get_clean();

It uses the output buffer control function ob_start() to buffer the following output until it’s returned by ob_get_clean().

Edit    Make sure that you validate the data passed to this function so that $vars doesn’t has a file element that would override the passed $file argument value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download