Home >Backend Development >PHP Tutorial >php怎么执行变量里的PHP模板代码?

php怎么执行变量里的PHP模板代码?

WBOY
WBOYOriginal
2016-06-06 20:43:411020browse

<code class="lang-php">$tpl = '

<div><?php echo $a ?></div>

';
$a = '我是变量a';

//怎么把$tpl变量解析成 

<div>我是变量a</div>


</code>

我自己Google到答案了 eval(' ?>'.$tpl.'

回复内容:

<code class="lang-php">$tpl = '

<div><?php echo $a ?></div>

';
$a = '我是变量a';

//怎么把$tpl变量解析成 

<div>我是变量a</div>


</code>

我自己Google到答案了 eval(' ?>'.$tpl.'

直接保存为文件比如 filename.tpl, 然后引入就可以了,简单的模板实现:

<code>function view($filename, Array $data) {
    extract($data);
    include $filename.'.tpl';
}
</code>

不考虑安全问题的话,可以把 $tpl 的内容写入一个临时文件,再 require 进来

<code><?php $tpl = '<div><?php echo $a ?>';
$a = '我是变量a';

file_put_contents('tmp.php', $tpl);
ob_start();
require 'tmp.php';
$parsed_content = ob_get_clean();
unlink('tmp.php');
?>
</code>

包含,然后PHP 去解析

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn