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

WBOY
Release: 2016-06-06 20:43:41
Original
994 people have browsed it

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

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

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

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

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


</code>
Copy after login
Copy after login

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

回复内容:

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

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

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

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

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


</code>
Copy after login
Copy after login

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

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

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

不考虑安全问题的话,可以把 $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>
Copy after login

包含,然后PHP 去解析

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!