php实现页面静态化

首先明白php实现页面静态化是将php文件生成相应的.shtml文件,那.shtml是什么文件呢?

包含有嵌入式服务器方包含命令的HTML(标准通用标记语言下的一个应用)文本。在被传送给浏览器之前,服务器会对SHTML文档进行完全地读取、分析以及修改。

以下是实例代码:

 <meta charset="utf-8" http-equiv="content-type" />
 <?php
	
	//首先查看缓存文件
	if(file_exists("static.html")){
		//缓存时间为3分钟
		if(time()-filemtime("static.html")<60*3){       //当前时间减去static.html生成时间,也就是当超过180s,则进行更新一遍
			//将静态文件内容返回给客户端
			$start_time = microtime();
			echo "我是从静态文件中读取的数据:"."<br/>";
			echo file_get_contents("static.html");
			$end_time   = microtime();
			echo "静态文件使用时间:".($end_time-$start_time);
			exit;
		}
	}
	//如果是首次访问,或者是上次缓存的时间超过3分钟,则从数据库中读取数据
	$host     = "127.0.0.1";
	$user     = "root";
	$password = "yuyouwen";
	//记录开始时间
	$start_time = microtime();
	mysql_connect($host,$user,$password);
	mysql_select_db("shucai");
	mysql_query("set names utf8");
	
	$sql 		= "SELECT username,password FROM admin";
	$resource 	= mysql_query($sql);
	echo "我是从数据库中读取的数据:<br/>";
	ob_start();//打开输出缓冲
	echo "<table border='1'><tr><th>姓名</th><th>地址</th></tr>";
	//输出取得的信息
	while($userInfo = mysql_fetch_assoc($resource)){
		echo "<tr>";
		echo "<td>".$userInfo['username']."</td>";
		echo "<td>".$userInfo['password']."</td>";
		echo "</tr>";
	}
	$end_time=microtime();
	$str=ob_get_contents();//获取缓冲区的内容
	ob_end_flush();
	
	echo "从数据库读数据的时间:".($end_time-$start_time);
	
?>

  代码其实生成的是html文件,这时在 file_put_contents("static.html",$str);

  中的static.html改成static.shtml也行

 还有要说明的是,顶部一行代码是编码的格式,少了这行会出现乱码,即中文不能正确显示,


 

结果说明:

index.php页面的结果:

static.html页面的结果:

file_put_contents("static.html",$str); 中奖static.html改成static.shtml后的结果:

结果是shtml 识别不了html 的格式是不是啊?还是ssi未打开的问题还是什么的?解决了再回来更新


 

 

更新

因为获得的static.html页面是从缓冲区获得,所以也就是没有字符编码格式,后来在 echo "<table border='1'><tr><th>姓名</th><th>地址</th></tr>"; 的前面加入一行

echo "<meta charset='utf-8' http-equiv='content-type' />";

则字符编码显示正确:

接下来解决的是生成shtml的问题

posted @ 2015-04-27 16:36  todaytoday  阅读(643)  评论(0编辑  收藏  举报