当前位置:Gxlcms > PHP教程 > 使用ob_start缓冲输出做简单缓存_PHP教程

使用ob_start缓冲输出做简单缓存_PHP教程

时间:2021-07-01 10:21:17 帮助过:7人阅读

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做简单缓存。

  1. <!--?php
  2. $time1 = microtime(true);
  3. for($i = 0;$i < 9999;$i++)
  4. {
  5. //echo $i.'<br /-->';
  6. }
  7. echo "<br>";
  8. $time2 = microtime(true);
  9. echo $time2 -$time1;
  10. //
输出 0.0010678768158 ?>

没做缓存的时候,运行时间为 0.0010678768158。

1. 简单缓存

  1. <!--?php
  2. $time1 = microtime(true);
  3. $cache_file = "file.txt";
  4. if(file_exists($cache_file))
  5. {
  6. $info = file_get_contents($cache_file);
  7. echo $info;
  8. $time2 = microtime(true);
  9. echo $time2 -$time1;
  10. exit();
  11. }
  12. ob_start();
  13. for($i = 0;$i < 9999;$i++)
  14. {
  15. //echo $i;
  16. }
  17. echo "<br /-->";
  18. $info = ob_get_contents();
  19. file_put_contents($cache_file ,$info);
  20. $time2 = microtime(true);
  21. echo $time2 -$time1;
  22. //
输出 0.00075888633728 ?>

没做缓存耗时 0.001秒,做了简单缓存则为 0.0007秒,缓存后速度稍有提升。

2. 进一步缓存

在前面缓存的基础上进一行加深。大家都知道,js文件不仅不耗费服务器的资源,同时会被下载到客户端,秩序下载一次,之后就不消耗带宽了,缺点就是不可以被搜索引擎抓到包,但是对于办公系统来说,是一个非常好的选择。

  1. <!--?php
  2. $time1 = microtime(true);
  3. function htmltojs($str)
  4. {
  5. $re='';
  6. $str=str_replace('\','\\',$str);
  7. $str=str_replace("'","'",$str);
  8. $str=str_replace('"','"',$str);
  9. $str=str_replace('t','',$str);
  10. $str= split("rn",$str); //已分割成数组
  11. for($i=0;$i < count($str); $i++)
  12. {
  13. $re.="document.writeln("".$str[$i]."");rn"; //加上js</pre-->输出
  14. }
  15. $re = str_replace("");
  16. document.writeln("","",$re);
  17. return $re;
  18. }
  19. $cache_file = "file.js";
  20. if(file_exists($cache_file))
  21. {
  22. $info = file_get_contents($cache_file);
  23. show_script($cache_file);
  24. $time2 = microtime(true);
  25. echo $time2 -$time1;
  26. exit();
  27. }
  28. ob_start();
  29. for($i = 0;$i < 9999;$i++)
  30. {
  31. //echo $i;
  32. }
  33. echo "<br>";
  34. $info = ob_get_contents();
  35. $info = htmltojs($info);
  36. file_put_contents($cache_file ,$info);
  37. $time2 = microtime(true);
  38. echo $time2 -$time1;
  39. ?>

只是简单地提供一个缓存的思路。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/752543.htmlTechArticlePHP ob_start()函数是一个功能强大的函数,可以帮助我们处理许多问题。 Output Control 函数可以让你自由控制脚本中数据的输出。它非常地有用...

人气教程排行