Last Updated: June 11, 2021
·
30.49K
· masquerade

"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.

5 Responses
Add your response

Thanks a lot!

over 1 year ago ·

Perfect function, work like a charm! Thanks.

over 1 year ago ·

This is perfect function for me! Thanks a lot

over 1 year ago ·

Thank you

over 1 year ago ·

it's really really perfect function! Thanks a lot

over 1 year ago ·