Smarty实现HTML静态化页面

时间:2023-03-09 04:07:44
Smarty实现HTML静态化页面
<?php
require_once("./config/config.php");

ob_start();
$id=$_GET[id];
$sql="select * from table_name where id='$id'";
$result=mysql_query($sql);
$rs=mysql_fetch_object($result);
$smarty->assign("showtitle",$rs->title);
$smarty->assign("showcontent",$rs->content);
$smarty->display("content.html");
$this_my_f= ob_get_contents(); 
ob_end_clean();
$filename = "$id.html";
tohtmlfile_cjjer($filename,$this_my_f);
// 文件生成函数
function tohtmlfile_cjjer($file_cjjer_name,$file_cjjer_content){
if (is_file ($file_cjjer_name)){
@unlink ($file_cjjer_name); //存在,就删除
}
$cjjer_handle = fopen ($file_cjjer_name,"w"); //创建文件
if (!is_writable ($file_cjjer_name)){ //判断写权限
return false;
}
if (!fwrite ($cjjer_handle,$file_cjjer_content)){
return false;

fclose ($cjjer_handle); //关闭指针
return $file_cjjer_name; //返回文件名
}
?>
最后在将生成的静态页面发布到web上。

第二种方式:

这款生成静态页面的方法与其它的有一点不同,这是利用smarty模板引擎的fetch函数,由smarty解析的文件保存到一个变量,然后再利用fopen 创建文件,此方法不适合大数据量生成。
*/

include('./www.update8.com/smarty/smarty.class.php');
$smarty = new smarty();
$smarty->template_dir = "templates/";
$smarty->compile_dir = "templates_c/";
$smarty->left_delimiter = "<{";
$smarty->right_delimiter = "}>";

$db = mysql教程_connect('localhost','root','');
mysql_select_db('test');
mysql_query('set names "utf8"');
$result = mysql_query('select * from news');
while($row[] = mysql_fetch_array($result)){
 $smarty->assign('news',$row);
}
//$smarty->display('smarty_html.html');
//以上不用写注释你都能看懂
//这里我们不显示他
//而是获得他
$content = $smarty->fetch('smarty_html.html');
//获得smarty替换都的模板文件内容也就是display之后的smarty_html.php的内容
/*
 其实这一步就相当于这样
 ob_start(); 开启缓冲区
 $smarty->display('smarty_html.html');
 $content = ob_get_contents(); 获得缓冲区内容
 ob_end_claen;关闭缓冲区
*/
makehtml('news.html',$content);//写入内容到news.html文件
echo '<a href="http://jiangyanan0425.blog.163.com/blog/news.html">查看</a>';
//点击查看静态页面就生成成功了!
//但是有个问题就是必须在当前页面才行
//比如你在另外一个php文件里$smarty->fetch('smarty_html.html');
//只能得到原本的模板文件内容,因为没有assign所以所有的模板变量都没替换
//生成了也是费的!
function makehtml($file,$content){
 $fp = fopen($file,'w');
 fwrite($fp,$content);
 fclose($fp);
}
?>

//模板页面

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<{section name=n loop=$news}>
id  <{$news[n].news_id}><br />
title  <{$news[n].news_title}> <br />
content<{$news[n].news_content}>
<hr />
<{sectionelse}>
暂时没有新闻
<{/section}>
</body>
</html>