"Compressing" HTML output with PHP
A very simple way to "Compress" your HTML output with PHP is to use the ob_start() function with a callback function that removes unwanted newlines. tabs etc.
The simplest way is to do the following.
function ob_html_compress($buf){
return str_replace(array("\n","\r","\t"),'',$buf);
}
ob_start("ob_html_compress");
// Your Code
ob_end_flush();
You should also enable GZIP in the PHP config using zlib.outputcompression rather than using obgzhander() as your ob_start() callback.
But of course it might be a good idea to extend the obhtmlcompress function to filter out a bit more of unnecessary output, if you just replace the function body with.
return preg_replace(array('/<!--(.*)-->/Uis',"/[[:blank:]]+/"),array('',' '),str_replace(array("\n","\r","\t"),'',$buf));
Then you will filter out multiple spaces and HTML comments as well.
Written by Philipe Rubio
Related protips
5 Responses
Thanks a lot!
Perfect function, work like a charm! Thanks.
This is perfect function for me! Thanks a lot
Thank you
it's really really perfect function! Thanks a lot
Have a fresh tip? Share with Coderwall community!
PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.
Security insights from Cside