Compressing Output

Output buffering allows you to compress the HTML you send to your visitors, which makes your site load faster for your users and also allows you to make more use of the bandwidth allocated to your server.

Whenever a visitor connects to your site, she sends along information such as the last page she visited, the name of the web browser she is using, and what content and encoding she accepts. The encoding part is what we're interested in—if a browser supports compressed HTML, it sends word of this to the web server each time it requests a page. The web server can then send back compressed HTML if told to do so—this is important, because browsers that do not support compressed HTML will always get plain HTML back, so this works for everyone.

Compressed HTML is literally the zipped version of the normal HTML a browser would otherwise have received; the client unzips it, then reads it as normal. As zipping information requires that you must know all the information before you compress it, output buffering is perfect—you send all your data to a buffer, zip the buffer, and send it off to your users.

As the tie between output buffering and output compression is so close, the code to make it work is equally close. To enable it, just pass the ob_gzhandler parameter to ob_start(); that will automatically check whether content compression is supported, and enable it, if it is. For example:

 ob_start("ob_gzhandler") // output content for compression here ob_end_flush(); ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.