t1.php
复制代码 代码如下:
<?php
// 方法一根据模版生成静态页面
// replaceTemplateString函数用于替换模板中指定字符串
function replaceTemplateString($templateString) {
// 用来替换的变量
$title = "文章标题";
$body = "这里是文章主体";
// 替换模板中指定字符串
$showString = str_replace ( "%title%", $title, $templateString );
$showString = str_replace ( "%body%", $body, $showString );
// 返回替换后的结果
return $showString;
}
$template_file = "template.html";
$new_file = "new.html";
// 模版文件指针
$template_juBing = fopen ( $template_file, "r" );
// 要生成的文件指针
$newFile_juBing = fopen ( $new_file, "w" );
// 方式一获取整体模板内容字符串,替换后赋给新文件
$templateString = fread ( $template_juBing, filesize ( $template_file ) );
$showString = replaceTemplateString ( $templateString ); // 替换模板中字符串
fwrite ( $newFile_juBing, $showString ); // 将替换后的内容写入生成的HTML文件
// 关闭文件指针
fclose ( $newFile_juBing );
fclose ( $template_juBing );
// 方法二根据缓冲区生成
ob_start (); // 当缓冲区激活时,并且有ob_end_clean()的情况下,所有输出打印的非文件头信息均不会输出打印到页面,而是保存在内部缓冲区。如果没有ob_end_clean(),则信息既被存在内部缓冲区,也被输出打印
?>
this is test Output Control
<?php
echo "<br>this is test Output Control<br>";
include_once 'cache/newFile.php';
$contents = ob_get_contents (); // 获取缓冲区到此为止存储的信息,缓冲区只保存会向页面浏览器输出打印的内容,php执行代码等不会保存
// $contents = ob_get_clean(); // 获取缓冲区到此为止存储的信息,并关闭清除缓冲区
// ob_end_flush();//输出打印缓冲区到此为止存储的信息,并关闭清除缓冲区
ob_end_clean (); // 关闭清除缓冲区的内容
file_put_contents ( $new_file, $contents );// 向文件写入内容
?>
template.html
复制代码 代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>%title%</title>
</head>
<body>
<H1>%title%</H1>
<hr>
<pre>%body%</pre>
</body>
</html>