PHP使用OB缓存实现静态化功能示例

2025-05-29 0 50

本文实例讲述了PHP使用OB缓存实现静态化功能。分享给大家供大家参考,具体如下:

实现步骤

1、创建测试数据表并且写入数据

2、实现后台的更新操作。使用OB缓存针对每一个内容生成对应的HTML文件

3、显示前台的数据信息

具体实现

①创建测试数据表并且写入数据(test.sql文件):

?

1

2

3

4

5

6

7

8

9
#创建数据表

create table news(

id int auto_increment,

title varchar(100) not null default '',

body text,

primary key(id)

)engine =myisam default charset=utf8;

#数据写入

insert into news values(null,'静态化','静态化可以减少服务器压力'),(null,'伪静态','伪静态能够满足SEO优化');

②实现后台的更新操作(admin.php文件)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32
<?php

//具体的后台更新

//获取所有的数据信息

mysql_connect('127.0.0.1','root','123456');

mysql_select_db('test');

$sql='select * from news';

$res = mysql_query($sql);

while ($row=mysql_fetch_assoc($res)) {

//针对每一条数据生成html文件

ob_start();//开启OB缓存

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>静态化介绍</title>

</head>

<body>

<h1><?php echo $row['title']; ?></h1>

<div><?php echo $row['body']; ?></div>

</body>

</html>

<?php

//获取OB缓存中的内容

$str = ob_get_contents();

//关闭OB缓存并且清空内容。因为如果不清空浏览器上会看到所有的数据结果

ob_end_clean();

//将信息写入到文件中 关于具体的文件目录及文件名称需要自定义

//对于在实际项目中关于html文件的存储 一般都会使用年月日的格式存在

file_put_contents($row['id'].'.html',$str);

}

?>

③实现前台数据显示(list.php文件):

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32
<?php

//显示列表

//获取所有的数据信息

mysql_connect('127.0.0.1','root','123456');

mysql_select_db('test');

$sql='select * from news';

$res = mysql_query($sql);

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>静态化介绍</title>

</head>

<body>

<h1>显示列表</h1>

<table>

<tr>

<td>序号</td>

<td>标题</td>

<td>查看</td>

</tr>

<?php while ($row =mysql_fetch_assoc($res)) {?>

<tr>

<td><?php echo $row['id']; ?></td>

<td><?php echo $row['title']; ?></td>

<td><a href="<?php echo $row['id'];?>.html" rel="external nofollow" > 查看</a></td>

</tr>

<?php } ?>

</table>

</body>

</html>

希望本文所述对大家PHP程序设计有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 PHP使用OB缓存实现静态化功能示例 https://www.kuaiidc.com/93140.html

相关文章

发表评论
暂无评论