08 October 2009

Using output buffering

I prefer to use output buffering. It's useful if you have a page which have a lot of dynamic content that needs to be processed or rendered. It prevents that the page loads in parts. It will allow that the output is sent all at once to the user's browser.

I start and end the buffering at the beginning and end of my layout script.

To start put ob_start() at the beginning. This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

To end put ob_end_flush() at the end of the layout script. This function will send the contents of the topmost output buffer (if any) and turn this output buffer off.

There is also other function regarding output buffering available:

  • ob_get_contents() - Return the contents of the output buffer
  • ob_get_flush() - Flush the output buffer, return it as a string and turn off output buffering
  • ob_flush() - Flush (send) the output buffer
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering

You can also gzip the output of the buffer. For that you have to call ob_start('ob_gzhandler'). But that should generate a warning as content is already being gzipped normally. To use this you have to turn off output compression in the php settings. Not recommended.

1 comment:

  1. Do you have a code example that you can share of this in use? I've tried various combinations of ob_start() and ob_flush() but none of them produce the results I'm looking for, which is to send the head element data first and the body element data afterwards.