假设有这样一个需求,我们需要在页面中显示一句话。这个话有可能是变更的,但是显示这句话的页面模板不会变。
首先定义页面模板:
<html>
<head>
<title>No Title</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
</head>
<body>
Hi,<?php echo $texts['name'];?>! Welcome to the php world.
</body>
</html>主要就是显示$texts['name']中的文字。那么再定义根据模板生成页面的代码。
<?php
$arr = array(
'texts'=>array('name' => 'wolongju')
);
$FILE_PATH = '/home/administrator/workspace/PHPLearn';
list($microseconds,$seconds) = explode(' ',microtime());
$filename = $seconds.$microseconds.getmypid();
$filename = $FILE_PATH .'/'.str_replace('.', "",$filename).'.php';
extract($arr);
ob_start();
require('index.tpl.php');
$out = ob_get_clean();
$f = fopen($filename,'w');
fwrite($f, $out);
fclose($f);
echo "Execute Complete.";
?>这样执行以上代码,就可以生成页面。即:
<html>
<head>
<title>No Title</title>
<meta http-equiv="Content-Type" type="text/html;charset=utf-8"/>
</head>
<body>
Hi,wolongju! Welcome to the php world.
</body>
</html>
本文介绍了一种使用PHP动态生成HTML页面的方法。通过定义页面模板并利用PHP代码填充变量,可以快速生成包含特定内容的网页。示例展示了如何将变量注入到模板中,并通过输出缓冲来捕获和保存生成的页面。
446

被折叠的 条评论
为什么被折叠?



