这是本人根据自己学习PHP技术页面静态化的过程所写的学习笔记,希望能够对大家有所帮助。
1、基本思路:
(1)用户第一次访问这个页面时从数据库读出内容,放在缓存中;
(2)将缓存中的数据写成一个html静态页面的文件;
(3)用户以后访问都去读取生成html文件,然后输出在屏幕上;
(4)每隔一定的时间重新生成一次html静态页面。
2、创建数据库
create table news(
id int unsigned primary key auto_increment,
title varchar(128) not null,
content varchar(256) not null,
filename varchar(32)) engine=MyISAM
3、测试数据
INSERT INTO `static_pages_news`.`news` (`id`, `title`, `content`, `filename`) VALUES (NULL, 'hello1', '北京你好', NULL), (NULL, 'hello2', '四川你好', NULL);
4、代码
news_list.php(新闻列表页面)<?php
//新闻列表
//查询数据库,获取信息=>SqlHelper.class.php
$conn = mysql_connect("localhost", "root", "root");
if (!$conn) {
die("连接失败");
}
mysql_select_db("static_pages_news", $conn);
mysql_query("set names utf8");
$sql = "select * from news";
$res = mysql_query($sql);
header("content-type:text/html;charset=utf-8");
echo "<h1>新闻列表</h1>";
echo "<a href='#'>添加新闻</a><hr/>";
echo "<table>";
echo "<tr><td>id</td><td>标题</td><td>查看详情</td></tr>";
while ($row = mysql_fetch_assoc($res)) {
echo "<tr><td>{$row['id']}</td><td>{$row['title']}</td><td><a href='show_news.php?id={$row['id']}'>查看详情</a></td></tr>";
}
echo "</table>";
mysql_free_result($res);
mysql_close($conn);
?>
show_news.php(新闻详情页面)
<?php
$id = @$_GET['id'];
//构建文件名
$html_filename = "new_id" . $id . ".html";
$html_path = dirname(__FILE__) . "/" . $html_filename;
//判断html页面是否有并且页面最后修改时间到现在小于30s
if (file_exists($html_path) && filemtime($html_path) + 30 < time()) {
//直接访问html页面(把html页面的内容echo浏览器)
echo file_get_contents($html_path);
exit ;
}
$conn = mysql_connect("localhost", "root", "root");
if (!$conn) {
die("连接失败");
}
mysql_select_db("static_pages_news", $conn);
mysql_query("set names utf8");
$sql = "select * from news where id=$id";
$res = mysql_query($sql);
//开启缓存
ob_start();
if ($row = mysql_fetch_assoc($res)) {
header("content-type:text/html;charset=utf-8");
echo "<table border='1px' bordercolor='green' cellspacing='0' width=400px height=200px>";
echo "<tr><td>新闻详细内容</td></tr>";
echo "<tr><td>{$row['title']}</td></tr>";
echo "<tr><td>{$row['content']}</td></tr>";
echo "</table>";
} else {
echo "没有结果";
}
$html = ob_get_contents();
$my_header = "<head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /></head>";
//把ob写进html文档
file_put_contents($html_path, $my_header . $html);
mysql_free_result($res);
mysql_close($conn);
?>
5、不足之处
(1)在查看新闻详情的时候,仍然是一个PHP页面
(2)实时性不够好,有30s的延时