Can you render a PHP file into a variable?

依然范特西╮ 提交于 2019-12-18 11:13:49

问题


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


回答1:


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.




回答2:


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();

}



回答3:


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

Output buffering might be the place to start.




回答4:


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




回答5:


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



来源:https://stackoverflow.com/questions/761922/can-you-render-a-php-file-into-a-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!