smarty实现PHP静态化的两种方法分享

用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; //返回文件名
}
?>

方法二:
smarty中有一个获取模板页内容方法fetch(), 它的声明原形是这样的:

<?php
function fetch($resource_name, $cache_id = null,
$compile_id = null, $display = false)
?>

第一个参数为模板名称, 第二个参数为缓存的id, 第三个参数为编译id, 第四个参数为是否显示模板内容. 生成静态页我们就需要用到这个方法.

<?php
$smarty = new Smarty();
//其它模板替换语法...
//下面这句取得页面中所有内容, 注意最后一个参数为false
$content = $smarty->fetch('模板名称.tpl', null, null, false);
//下面将内容写入至一个静态文件
$fp = fopen('news.html', 'w');
fwrite($fp, $content);
fclose($fp);
//OK, 到这里这个news.html静态页就生成了, 你可以处理你下一步的工作了
?>

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

如何让自己的本地APACHE服务器支持”.htaccess”呢?其实只要简单修改一下apache的httpd.conf设置就可以让APACHE支持.htaccess了