php生成静态文件的多种方法分享


  本文标签:生成静态文件

第一种:将php动态页面内容生成静态
复制代码 代码如下:

ob_start();#开启服务器缓存
include_once Index.php;
$ctx=ob_get_contents();#获取缓存
ob_end_clean();#清空缓存
$fh=fopen("index.html","w+");
fwrite($fh,$ctx);#写入html,生成html
fclose($fh);
/*
1、Flush:刷新缓冲区的内容,输出 。
函数格式:flush()
说明:这个函数经常使用,效率很高 。
2、ob_start :打开输出缓冲区
函数格式:void ob_start(void)
说明:当缓冲区激活时,所有来自PHP程序的非文件头信息均不会发送,而是保存在内部缓冲区 。为了输出缓冲区的内容,可以使用ob_end_flush()或flush()输出缓冲区的内容 。
3 、ob_get_contents :返回内部缓冲区的内容 。
使用
函数格式:string ob_get_contents(void)
说明:这个函数会返回当前缓冲区中的内容,如果输出缓冲区没有激活,则返回 FALSE  。
4、ob_get_length:返回内部缓冲区的长度 。
使用方法:int ob_get_length(void)
说明:这个函数会返回当前缓冲区中的长度;和ob_get_contents一样,如果输出缓冲区没有激活 。则返回 FALSE 。
5、ob_end_flush :发送内部缓冲区的内容到浏览器,并且关闭输出缓冲区 。
使用方法:void ob_end_flush(void)
说明:这个函数发送输出缓冲区的内容(如果有的话) 。
6、ob_end_clean:删除内部缓冲区的内容,并且关闭内部缓冲区
使用方法:void ob_end_clean(void)
说明:这个函数不会输出内部缓冲区的内容而是把它删除!
7、ob_implicit_flush:打开或关闭绝对刷新
使用方法:void ob_implicit_flush ([int flag])
*/

第二种:
php 静态文件生成类(自家用)
复制代码 代码如下:

<?php
class CreateHtml
{
function mkdir( $prefix= article )
{
$y = date(Y);
$m = date(m);
$d = date(d);
$p=DIRECTORY_SEPARATOR;
$filePath=article.$p.$y.$p.$m.$p.$d;
$a=explode($p,$filePath);
foreach ( $a as $dir)
{
$path.=$dir.$p;
if(!is_dir($path))
{
//echo 没有这个目录.$path;
mkdir($path,0755);
}
}
return $filePath.$p;
}
function start()
{
ob_start();
}
function end()
{
$info = ob_get_contents();
$fileId = 12345;
$postfix = .html;
$path = $this->mkdir($prefix= article);
$fileName = time()._.$fileId.$postfix;
$file=fopen($path.$fileName,w+);
fwrite($file,$info);
fclose($file);
ob_end_flush();
}
}
?>
<?php
$s=new CreateHtml();
$s->start();
?>
<html>
<body>
asdfasdfasdfasdfasdfasdfasdfasdfasdf<br>
adfasdfasdf<br>
</body>>
</html>
<?php
$s->end();
?>