Smarty模板保留缓存

时间:2021-09-06 12:33:18
<?php
//缓存
//注:使用缓存需要用到这几个方法:
//(ob_start(开启内存缓存); ob_flush(清除内存缓存);)
//file_exists这个方法是判断文件是否存在
//assign("接受值"); display("传给另一个页面值"); 这个方法是一对要配合着用 //定义一个该页面的缓存文件路径交给$filename
$filename = "../cache/huancun_wenjian.html";
//设置一个缓存时间
$time = 5; //判断缓存文件是否存在 // ||
if(!file_exists($filename) || filemtime($filename)+$time<time()){ //开启内存缓存
ob_start(); include("../init.inc.php");
include("../DBDA.php");
$db = new DBDA(); $sql = "select * from nation";
$attr = $db->Query($sql); $smarty->assign("nation",$attr);
$smarty->display("huancun.html"); //把内存里面的内容读出来 交给$nr
$nr = ob_get_contents(); //将读到的内容存放到缓存文件
//将内存$nr里面所有读到的内容扔到缓存文件里面去
file_put_contents($filename,$nr); //清楚内存缓存
ob_flush(); echo "<a href='#'>我是缓存我只出现一次</a>"; }else{ //如果缓存文件存在就显示缓存文件
include($filename);
}
<!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>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
<td>代号</td>
<td>名称</td>
</tr>
<{foreach $nation as $v}>
<tr>
<td><{$v[0]}></td>
<td><{$v[1]}></td>
</tr>
<{/foreach}>
</table>
</body>
</html>

效果图

Smarty模板保留缓存

刷新后走的缓存页面

Smarty模板保留缓存