如果你读了上篇文章网站开发者的『输出缓冲』入门指导,你会发现 PHP output buffering 是很有用的.
回忆下上篇文章, output buffering 把 PHP 脚本的输出暂存到buffer中,从而代替直接向浏览器一点一点输出,
这就允许我们在用户看到页面前对整个页面进行自定义了。
我们继续用上篇文章的代码:
<?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 return $buffer;
}
?>
在下面的例子中我们会一直使用 ob_postprocess($buffer)
。
优化HTML,移除重复的空白
重复的空白并不会在浏览器中渲染出来,但是用户的浏览器依然会下载它们,我们应该只保留一个空格。像这样:
function ob_postprocess($buffer)
{
$buffer = trim(preg_replace('/\s+/', ' ', $buffer));
return $buffer;
}
使用 gzip 压缩HTML
function ob_postprocess($buffer)
{
if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
$buffer = gzencode($buffer);
header('Content-Encoding: gzip');
}
return $buffer;
}