发表日期:2017-03 文章编辑:小灯 浏览次数:580
如果你还没有使用 PHP 的output buffering
,那么现在开始吧!
这是一篇专门写给web developer
的文章,我会在几秒钟内举几个小李子让大家来明白什么是output buffering
。
简单来说,不使用 output buffering,你的网页(即 HTML)是在PHP执行时一段一段渲染到浏览器的;使用 output buffering 的话,你的
HTML 会被当做一个整体储存在一个变量中,然后一下子在浏览器中渲染出来,你是不是已经在思考性能上的优势以及网页传递时给你提供了某些可能?
Warning: Cannot modify header information - headers already sent by (output)
的问题,你会很开心 output buffering 就是答案<?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; } ?>
因为HTML并不直接发送到浏览器了,我们可以毫无顾忌的在我们的PHP脚本中设置COOKIE。赶紧 turn it on 吧!
更多其妙用法
日期:2019-02 浏览次数:6484
日期:2019-02 浏览次数:4221
日期:2019-02 浏览次数:3972
日期:2019-02 浏览次数:4449
日期:2019-02 浏览次数:4144
日期:2019-02 浏览次数:7303
日期:2019-02 浏览次数:4005
日期:2019-02 浏览次数:4496
日期:2019-02 浏览次数:4353
日期:2019-02 浏览次数:4022
日期:2019-02 浏览次数:4361
日期:2019-02 浏览次数:4143
日期:2019-02 浏览次数:4032
日期:2019-02 浏览次数:3956
日期:2019-02 浏览次数:4690
日期:2019-02 浏览次数:4154
日期:2019-02 浏览次数:4150
日期:2019-02 浏览次数:4204
日期:2019-02 浏览次数:4161
日期:2019-02 浏览次数:4079
日期:2019-02 浏览次数:4448
日期:2019-09 浏览次数:4475
日期:2019-09 浏览次数:4121
日期:2019-09 浏览次数:4135
日期:2019-09 浏览次数:4089
日期:2019-09 浏览次数:4067
日期:2019-09 浏览次数:4164
日期:2019-09 浏览次数:4111
日期:2019-09 浏览次数:4582
日期:2019-09 浏览次数:5099
Copyright ? 2013-2018 Tadeng NetWork Technology Co., LTD. All Rights Reserved.