Last active
August 29, 2015 14:03
-
-
Save gowon/184f52743fdf51121971 to your computer and use it in GitHub Desktop.
Minify PHP Output Buffer - Compress HTML output to a single line, then attempt gzip compression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Smart Tidy/Gzip Output Buffer | |
* Compress HTML output to a single line, then attempt gzip compression. | |
* @param string $buffer | |
* @param int $mode | |
* @return string|false | |
*/ | |
function ob_minify($buffer, $mode) { | |
$search = array( | |
'/<!--[^\[](.*?)-->/s' => '', | |
//'/ +/' => ' ', // Old way to remove extra whitespace, wasn't catching everything | |
'/\s{2,}/' => '', // New way catches everything, maybe that's too aggressive? | |
//"/<!–\{(.*?)\}–>|<!–(.*?)–>|[\t\r\n]|<!–|–>|\/\/ <!–|\/\/ –>|<!\[CDATA\[|\/\/ \]\]>|\]\]>|\/\/\]\]>|\/\/<!\[CDATA\[/" => '' | |
"/[\t\r\n]|<!–|–>|\/\/ <!–|\/\/ –>|<!\[CDATA\[|\/\/ \]\]>|\]\]>|\/\/\]\]>|\/\/<!\[CDATA\[/" => '' | |
); | |
$buffer = preg_replace(array_keys($search), array_values($search), $buffer); | |
/* Only gzip for content with a min size of 860 bytes | |
* | |
* The reasons 860 bytes is the minimum size for compression is twofold: (1) The overhead of compressing an object | |
* under 860 bytes outweighs performance gain. (2) Objects under 860 bytes can be transmitted via a single packet | |
* anyway, so there isn't a compelling reason to compress them. | |
*/ | |
if (ob_get_length() >= 860) { | |
return ob_gzhandler($buffer, $mode); | |
} | |
return $buffer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment