Hany function ob_gzhandler that help facilitate sending gz-encoded data to web browsers that support compressed web pages.
This is the way I do it, checking the extension it’s loaded and that it’s possible to start the encoding:
if (extension_loaded('zlib')) {//check extension is loaded
if(!ob_start("ob_gzhandler")) ob_start();//start HTML compression, if not normal buffer input mode
}