本文實例講述了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程序設計有所幫助。