方法简单说明如下:
1.使用文件函数得到静态页面的模板字符串,然后用str_replace函数将需要替换的东西替换了再写入到新的文件中。
2. 利用PHP的输出控制函数(Output Control)得到静态页面字符串,再写入到新的文件中。
1 |
$filemodel = "template/it.php" ; #模板地址 |
2 |
$file = fopen ( $filemodel , "rb" ); #打开模板,得到文件指针 |
3 |
$temp = fread ( $file , filesize ( $filemodel )); #得到模板文件html代码 |
方法一:ob_get_contents()
这是一种很方便的方法,也是很常用的方法,实现原理是:首先打开缓存,然后创建相应的静态页文件,写入缓存的内容,清空缓存。
示例:
2 |
$fn = date ( 'ymdhis' ).rand(1000,9999). 'html' ; |
3 |
require ( "supply.php" );#载入要生成静态页的文件,因为后台有ob_clen()所以在不会显示出来 |
4 |
$fs = fopen ( $fn , 'w' );#打开静态页文件 |
5 |
fwrite( $fs ,ob_get_contents());#生成静态文件 |
方法二:file_get_contents();
1 |
$fn = date ( 'ymdhis' ).rand(1000,9999). 'html' ; |
2 |
$url = 'http://' . $_SERVER [ 'HTTP_HOST' ]. "/" ;#注意 |
3 |
$content = file_get_contents ( $url ); |
下面对上面的注意进行一下解释,如果在些你使用的是仅仅是文件名,而不是URL那么您这个文件中如果有使用引用文件比如require (‘header.php’); 那么header.php中的内容将会显示不出来。
方法三:str_replace()
1 |
$filemodel = "supply.php" ; 字串5 $file = fopen ( $filemodel , "w+" ); |
2 |
$temp = fread ( $file , filesize ( $filemodel )); |
3 |
$temp = str_replace ( "[title]" , $title , $temp ); |
4 |
$temp = str_replace ( "[postTime]" , $postTime , $temp ); |
5 |
$temp = str_replace ( "[content]" , $content , $temp ); |
该方法适用于很简单的页面,如果supply.php中有使用引用文件比如require (‘header.php’);那么header.php中的内容将会显示不出来
在实际应用中,您可以写一个生成静态页的类,
18 |
var $message1 = "Error 1: You write class Shtml is Wrong ! The second parameter is 1 or 2 in this class!." ; |
19 |
var $message2 = "Error 2: The file write Error." ; |
21 |
function __construct ( $Url , $FileBag , $FolderRoot , $FolderName , $fileid ) |
24 |
$this ->FileBag = $FileBag ; |
25 |
$this ->FileRoot = $FolderRoot ; |
26 |
$this ->FileName = $FolderName ; |
27 |
$this ->fileid = $fileid ; |
32 |
public function loadcontent ( $Folder ) |
35 |
require_once $this ->Url; |
36 |
Shtml::writehtml ( $Folder ,ob_get_contents()); |
41 |
public function useFolder () |
45 |
$Folder = $this ->FileName; |
47 |
else if ( $this ->FileBag==2) |
49 |
$Folder = date ( 'Ymd' ,time()); |
53 |
exit ( $this ->message1); |
55 |
if (! is_dir ( $this ->FileRoot. $Folder )){ mkdir ( $this ->FileRoot. $Folder ,0700);} |
57 |
Shtml::loadcontent ( $Folder ); |
61 |
public function writehtml ( $Folder , $cache_value ) |
63 |
$file = fopen ( $this ->FileRoot. $Folder . '/' . $this ->fileid. '.html' , 'w+' ); |
64 |
fwrite( $file , $cache_value ); |