以下几行PHP代码可以简单的将数据渲染到html页面上。
/** * @param $filePath PHP模块文件路径 * @param $data 模版文件上用到的变量数组 * @return string 渲染后的html文件内容 */ function getHtmlContentByTpl($filePath, $data) { ob_start(); extract($data); include $filePath; $str = ob_get_contents(); ob_end_clean(); return $str; }使用示例:
模版文件内容template.php
<html> <head> <title><?php echo $name . "的主页"; ?></title> </head> <body> <p><?php echo $name . "的工作是:" . $job; ?></p> </body> </html> 测试代码 $data = array( 'name' => 'zhoumin', 'job' => 'SDE', ); $ret = getHtmlContentByTpl('./template.php', $data); file_put_contents('./a.html', $ret); 生成的hmtl文件内容a.html
<html> <head> <title>zhoumin的主页</title> </head> <body> <p>zhoumin的工作是:SDE</p> </body> </html>