tags:

views:

411

answers:

5

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..

+2  A: 

http://www.devshed.com/c/a/PHP/Output-Buffering-With-PHP/

Output buffering might be the place to start.

Daniel A. White
+9  A: 

You could use some function like this:

function renderPhpToString($file, $vars=null)
{
    if (is_array($vars) && !empty($vars)) {
        extract($vars);
    }
    ob_start();
    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.

Gumbo
better hope someone doesn't send $vars = array('file' => 'http://example.com/hax.php')
John Douthat
This is exactly what I'm looking for. There is no need to worry about user input in my case. Thanks!
danb
>>There is no need to worry about user input in my case.Your not just worried about user input here; a future developer could call the function with $vars = array('file' => 'http://example.com/whoops.php'), and then spend quite a time deubgging this.
@rmbarnes: That's a little too paranoid. If the future developer is an idiot, then he can spend all the time in the world trying to fix his own mistake. :)
Paolo Bergantino
As another aside - just make <code>$file</code> something innocuous like <code>$bargle</code>, instead of worrying about validating input.
b. e. hollenbeck
+1  A: 

You can do this with output buffering, but might be better of using one of the many template engines.

Tobias
+1  A: 

As Gumbo said you have to check for the $file variable, its a subtle bug that has already bitten me. I would use func_get_arg( i ) and have no variables at all, and a minor thing, i would use require.

function renderPhpToString( )
{
    if( is_array( func_get_arg(1) ) ) {
        extract( func_get_arg(1) );
    }
    ob_start();
    require func_get_arg( 0 );
    return ob_get_clean();

}
+1  A: 

regarding passing $vars = array('file' => '/etc/passwd');, you could use extract($vars, EXTR_SKIP);

mike wyatt