Home > php教程 > PHP源码 > body text

php ob_start()函数实现当前页面内容缓存输出

WBOY
Release: 2016-06-08 17:22:50
Original
826 people have browsed it

页面缓存就是把页面保存到一个文件中,下次读出时直接调用文件而不查询数据库,这里我们介绍利用ob_start()来实现。


 代码如下 复制代码

ob_start(); //打开缓冲区
phpinfo(); //使用phpinfo函数
$info=ob_get_contents(); //得到缓冲区的内容并且赋值给$info
$file=fopen(’info.txt’,’w’); //打开文件info.txt
fwrite($file,$info); //写入信息到info.txt
fclose($file); //关闭文件info.txt
//或直接用 file_put_content('info.txt',$info);
?>

以上的方法,可以把不同用户的phpinfo信息保存下来。

这里我们可以着重看看这个方法的使用技巧,用这个方法可以实现生成静态页面的便利!

并且用这个方法比用file_get_conents()的方法更合理更有效率。

简单的说个应用吧,比如想要把phpinfo()的内容写入文件,可以这样做:

 代码如下 复制代码

ob_start();
$phpinfo = phpinfo();
//写入文件
ob_end_flush();

或者还有这样的用途:

ob_start(); //打开缓冲区
echo "Hellon"; //输出
header("location:index.php"); //把浏览器重定向到index.php
ob_end_flush();//输出全部内容到浏览器

header()会发送一段文件头给浏览器,但是如果在header()之前已经有了任何输出(包括空输出,比如空格,回车和换行)就会报错。但是如果输出在ob_start()和ob_end_flush()之间,就会没有问题。因为在输出前打开了缓冲区,echo后面的字符就不会输出到浏览器,而是保留在服务器,知道使用flush才会输出,所以header()会正常执行。

当然,ob_start()还可以有参数,参数就是一个回调函数。例子如下:

 代码如下 复制代码

function callback($buffer)
{
  // replace all the apples with oranges
  return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
? >


It's like comparing apples to oranges.




ob_end_flush();
? >

以上程序会输出:



It's like comparing oranges to oranges. p>

至于更多的,就去官网的手册里看吧。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!