网站开发者的『输出缓冲』入门指导

如果你还没有使用 PHP 的output buffering,那么现在开始吧!

这是一篇专门写给web developer的文章,我会在几秒钟内举几个小李子让大家来明白什么是output buffering

简单来说,不使用 output buffering,你的网页(即 HTML)是在PHP执行时一段一段渲染到浏览器的;使用 output buffering 的话,你的
HTML 会被当做一个整体储存在一个变量中,然后一下子在浏览器中渲染出来,你是不是已经在思考性能上的优势以及网页传递时给你提供了某些可能?

优势

  • 开启 output buffering 会减少HTML的渲染次数(显然滴)
  • 所有用来处理字符串的函数,可以拿来处理整个网页了,毕竟它是一个变量了
  • 如果曾经遇到过 Warning: Cannot modify header information - headers already sent by (output) 的问题,你会很开心 output buffering 就是答案

Hello World

<?php
# start output buffering at the top of our script with this simple command
ob_start();
?>
<html>
    <body>
        <p>Hello World</p>
    </body>
</html>
<?php
# end output buffering and send our HTML to the browser as a whole
ob_end_flush();
?>

就是这么简单!

进一步,压缩输出

下面,将 ob_start() 改成 ob_start('ob_gzhandler'),这个小改动将会压缩我们的HTML,是页面的加载体积变小。

<?php
# start output buffering at the top of our script with this simple command
# we've added "ob_gzhandler" as a parameter of ob_start
ob_start('ob_gzhandler');
?>
<html>
<body>
    <p>Hello World!</p>
</body>
</html>
<?php
# end output buffering and send our html to the browser as a whole
ob_end_flush();
?>

更进一步,更改传输内容

下面,ob_start() 变成了 ob_start('ob_postprocess')ob_postprocess() 是我们自定义的一个方法,用来在输出到浏览器之前更改HTML内容,Hello World 将会改成 Aloha World

<?php
// start output buffering at the top of our script with this simple command
// we've added "ob_postprocess" (our custom post processing function) as a parameter of ob_start
ob_start('ob_postprocess');
?>

<html>
<body>
<p>Hello world!</p>
</body>
</html>

<?php
// end output buffering and send our HTML to the browser as a whole
ob_end_flush();

// ob_postprocess is our custom post processing function
function ob_postprocess($buffer)
{
    // do a fun quick change to our HTML before it is sent to the browser
    $buffer = str_replace('Hello', 'Aloha', $buffer);
    // "return $buffer;" will send what is in $buffer to the browser, which includes our changes
    return $buffer;
}
?>

提示,在 output buffering 开启的情况下,我们可以在任何时候设置 cookies 了。

因为HTML并不直接发送到浏览器了,我们可以毫无顾忌的在我们的PHP脚本中设置COOKIE。赶紧 turn it on 吧!

更多其妙用法

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,067评论 19 139
  • PHP的输出缓冲区 什么是缓冲区?简单而言,缓冲区的作用就是,把输入或者输出的内容先放进内存,而不显示或者读取.至...
    桖辶殇阅读 2,034评论 3 12
  • ob的基本原则:如果ob缓存打开,则echo的数据首先放在ob缓存。如果是header信息,直接放在程序缓存。当页...
    金星show阅读 1,050评论 0 1
  • php.ini设置,上传大文件: post_max_size = 128Mupload_max_filesize ...
    bycall阅读 6,872评论 3 64
  • 我想你们再陪我玩一次这些东西 我想你们再陪我背着书包手牵手一起玩到天黑才回家 我不曾变过 喜好 喜欢的人还是你们 ...
    治愈系小妖飞儿阅读 213评论 0 0