欢迎您光临深圳塔灯网络科技有限公司!
电话图标 余先生:13699882642

网站百科

为您解码网站建设的点点滴滴

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

发表日期:2017-03 文章编辑:小灯 浏览次数:580

如果你还没有使用 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 吧!

更多其妙用法


本页内容由塔灯网络科技有限公司通过网络收集编辑所得,所有资料仅供用户学习参考,本站不拥有所有权,如您认为本网页中由涉嫌抄袭的内容,请及时与我们联系,并提供相关证据,工作人员会在5工作日内联系您,一经查实,本站立刻删除侵权内容。本文链接:http://www.dengtar.com/13344.html
相关企业建站知识
 八年  行业经验

多一份参考,总有益处

联系深圳网站公司塔灯网络,免费获得网站建设方案及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:余经理:13699882642

Copyright ? 2013-2018 Tadeng NetWork Technology Co., LTD. All Rights Reserved.