php ob_start()函数是一个功能强大的函数,可以帮助我们处理许多问题。
Output Control 函数可以让你自由控制脚本中数据的输出。它非常地有用,特别是对于:当你想在数据已经输出后,再输出文件头的情况。输出控制函数不对使用header() 或setcookie(), 发送的文件头信息产生影响,只对那些类似于echo() 和PHP 代码的数据块有作用。
所有对header()函数有了解的人都知道,这个函数会发送一段文件头给浏览器,但是如果在使用这个函数之前已经有了任何输出(包括空输出,比如空格,回车和换行)就会提示出错。如果我们去掉第一行的ob_start(),再执行此程序,我们会发现得到了一条错误提示:"Header had all ready send by"!但是加上ob_start,就不会提示出错,原因是当打开了缓冲区,echo后面的字符不会输出到浏览器,而是保留在服务器,直到你使用flush或者ob_end_flush才会输出,所以并不会有任何文件头输出的错误!
下面介绍下如何使用ob_start做简单缓存。
<?php
$time1 = microtime(true);
for($i = 0;$i < 9999;$i++)
{
//echo $i.'<br />';
}
echo "<br />";
$time2 = microtime(true);
echo $time2 -$time1;
// 输出 0.0010678768158
?>
没做缓存的时候,运行时间为 0.0010678768158。
立即学习“PHP免费学习笔记(深入)”;
<?php
$time1 = microtime(true);
$cache_file = "file.txt";
if(file_exists($cache_file))
{
$info = file_get_contents($cache_file);
echo $info;
$time2 = microtime(true);
echo $time2 -$time1;
exit();
}
ob_start();
for($i = 0;$i < 9999;$i++)
{
//echo $i;
}
echo "<br />";
$info = ob_get_contents();
file_put_contents($cache_file ,$info);
$time2 = microtime(true);
echo $time2 -$time1;
// 输出 0.00075888633728
?>
没做缓存耗时 0.001秒,做了简单缓存则为 0.0007秒,缓存后速度稍有提升。
在前面缓存的基础上进一行加深。大家都知道,js文件不仅不耗费服务器的资源,同时会被下载到客户端,秩序下载一次,之后就不消耗带宽了,缺点就是不可以被搜索引擎抓到包,但是对于办公系统来说,是一个非常好的选择。
<?php
$time1 = microtime(true);
function htmltojs($str)
{
$re='';
$str=str_replace('','\',$str);
$str=str_replace("'","'",$str);
$str=str_replace('"','"',$str);
$str=str_replace('t','',$str);
$str= split("rn",$str); //已分割成数组
for($i=0;$i < count($str); $i++)
{
$re.="document.writeln("".$str[$i]."");rn"; //加上js输出
}
$re = str_replace("");
document.writeln("","",$re);
return $re;
}
$cache_file = "file.js";
if(file_exists($cache_file))
{
$info = file_get_contents($cache_file);
show_script($cache_file);
$time2 = microtime(true);
echo $time2 -$time1;
exit();
}
ob_start();
for($i = 0;$i < 9999;$i++)
{
//echo $i;
}
echo "<br />";
$info = ob_get_contents();
$info = htmltojs($info);
file_put_contents($cache_file ,$info);
$time2 = microtime(true);
echo $time2 -$time1;
?>
只是简单地提供一个缓存的思路。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号