Render PHP to String

Article by on April 3, 2012

Say you have a file and you want to render it the way 'include' does, but you want to assign the contents to a string.

Option 1: Eval Statements

You can render the PHP through eval statements. However, a simple eval statement doesn't work. You need to extract only the PHP statements and then evaluate those statements. (You can't evaluate HTML, which makes perfect sense--it's not PHP code.)

class PhpStringParser
{
    protected $variables;

    public function __construct($variables = array())
    {
        $this->variables = $variables;
    }

    protected function eval_block($matches)
    {
        if( is_array($this->variables) && count($this->variables) )
        {
            foreach($this->variables as $var_name => $var_value)
            {
                $$var_name = $var_value;
            }
        }

        $eval_end = '';

        if( $matches[1] == '<?=' || $matches[1] == '<?php=' )
        {
            if( $matches[2][count($matches[2]-1)] !== ';' )
            {
                $eval_end = ';';
            }
        }

        $return_block = '';

        eval('$return_block = ' . $matches[2] . $eval_end);

        return $return_block;
    }

    public function parse($string)
    {
        return preg_replace_callback('/(\<\?=|\<\?php=|\<\?php)(.*?)\?\>/', array(&$this, 'eval_block'), $string);
    }
}

Then, to render the file you can do:

$p = new PhpStringParser();
$contents = $p->parse(file_get_contents('file.php'));

This method works well if the file only has HTML and some PHP variables. I found that with foreach loops and functions it would not work.

Source: http://us3.php.net/manual/en/function.eval.php#108091

Option 2: Output Buffer

Using output buffers seems to be the most reliable method. Essentially it includes the file and PHP renders it as it normally would. However, it captures all of the content in the output in the buffer, removes the contents from the buffer, and returns the contents (all part of ob_clean).

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

Then, to render the file you can do:

$contents = renderPhpToString('file.php');

Thank you Gumbo on StackOverflow!

Source: http://stackoverflow.com/a/761941/990642

Older Articles »