fatjmw
Last Updated: April 10, 2016
·
16.23K
· 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.

Say Thanks
Respond

5 Responses
Add your response

7536
Default profile 1 normal

Thanks a lot!

over 1 year ago ·
10304
E9035cebd0ab3cbbc988a7d1087a703c

Perfect function, work like a charm! Thanks.

over 1 year ago ·
17830
Au6n4sn2 normal

This is perfect function for me! Thanks a lot

over 1 year ago ·
24526
0 gicttdlbyh4imgl dsz70ztqrpwimtsmkfsfqy1qx6zeichgss97xjibjtwiatwgdss3jfxfcxcodnuiazbgsjlitxcwdnugszbclpr6mlgff8by3da2aeoc lduknr1xris9gctiib

Thank you

over 1 year ago ·
27495

it's really really perfect function! Thanks a lot

over 1 year ago ·