使用 PHP 输出缓冲区压缩 XHTML 页面输出

我们程序员喜欢保持代码的可读性和整洁性,这就是我们在代码中使用数百个制表符和换行符的原因。在 Web 编程世界中这样做的问题是我们的用户不关心我们整齐缩进的代码。他们不关心我们详细的代码注释。他们当然不关心选项卡辩论中的二对三对四空格。那么我们为什么要让他们下载额外的代码呢?使用一些快速的 PHP 代码,您就不需要了。

PHP代码

整个系统在一些非常短的 PHP 代码上运行:

<?php
	/*  start the output buffer  */
	ob_start('compress_page');

	/*  xhtml code below  */
?>
<!-- all xhtml content here -->
<?php
	/*  end the buffer, echo the page content  */
	ob_end_flush();

	/*  function that gets rid of tabs, line breaks, and extra spaces  */
	function compress_page($buffer) {
		$search = array('/>[^S ]+/s', '/[^S ]+</s', '/(s)+/s');
		$replace = array('>', '<', '1');
		return preg_replace($search, $replace, $buffer);
	}
?>

就是这样。压缩页面很容易实现,尤其是当您的网站使用 MVC 系统时。

赞(0) 打赏

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏