可以将PHP文件渲染为变量吗? [英] Can you render a PHP file into a variable?
本文介绍了可以将PHP文件渲染为变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的hello.php文件:
If I have a hello.php file like this:
Hello, <?php echo $foo; ?>!
我想在一些php代码中做类似的事情:
I would like to do something like this in some php code:
$text = renderPhpToString('hello.php', array('foo'=>'World'));
最后以
$text == 'Hello, World!'
使用标准PHP 5可以做到吗?显然,我希望使用带有循环等的更复杂的模板.
Is this possible with standard PHP 5? Obviously I want more complex templates with loops and so forth..
推荐答案
您可以使用以下功能:
function renderPhpToString($file, $vars=null)
{
if (is_array($vars) && !empty($vars)) {
extract($vars);
}
ob_start();
include $file;
return ob_get_clean();
}
它使用输出缓冲区控制功能 ob_start()
缓冲以下输出,直到由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()
.
编辑.请确保您验证传递给此函数的数据,以使$vars
的file
元素不会覆盖传递的$file
参数值.
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.
这篇关于可以将PHP文件渲染为变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文