PHP – ob_start()函数
1 |
bool ob_start ([ callback $output_callback [, int $chunk_size = 0 [, bool $erase = true ]]] ) |
打开输出缓存(output buffering)
简单的说个应用吧,比如想要把phpinfo()的内容写入文件,可以这样做:
1 2 3 4 |
ob_start(); $phpinfo = phpinfo(); //写入文件 ob_end_flush(); |
或者还有这样的用途:
1 2 3 4 |
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()还可以有参数,参数就是一个回调函数。例子如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
< ? php function callback($buffer) { // replace all the apples with oranges return (str_replace("apples", "oranges", $buffer)); } ob_start("callback"); ? > < html > < body > <p>It's like comparing apples to oranges.</p> < / body > < / html > < ?php ob_end_flush(); ? > |
以上程序会输出:
1 2 3 4 5 |
< html > < body > < p>It's like comparing oranges to oranges.</ p > < / body > < / html > |
至于更多的,就去官网的手册里看吧。
这里还有个算是稍微详细的说明,就是很凌乱…改日再整理:http://apps.hi.baidu.com/share/detail/33989046