Google-Like Compression
2011 Apr 30 08:15 PM MDT | PHP4 Programming18 Web13 [2011]3
I have a PHP object buffer callback that allows you to compress your PHP like Google:
<?php
function op_handler($buffer, $mode) { // overpowered handler xD
// tabs
$buffers = explode("</script>", $buffer);
foreach($buffers as &$buffer) {
$tabsearch = array(
'/[\t]+/' => '', // strip tabs
'/\s+/' => ' ', // multi-spaces
);
$jssearch = array(
'/\s+<!--/' => '<!--', // comment start
'/-->\s+/' => '-->', // comment end
);
$buffer = explode("<script", $buffer, 2);
$buffer[0] = preg_replace(array_keys($tabsearch), array_values($tabsearch), $buffer[0]);
$buffer[1] = preg_replace(array_keys($jssearch), array_values($jssearch), $buffer[1]);
$buffer = implode("<script", $buffer);
}
$buffer = implode("</script>", $buffers);
// gzip!
return ob_gzhandler($buffer, $mode);
}
ob_start("op_handler");
// ...output the page here...
It does tries to compress it by stripping tabs and compacting spaces without affecting the *<script>* tags. Then it gzips it using Apache's mod\_deflate.