WP-Mix

A fresh mix of code snippets and tutorials

PHP output buffering example

PHP’s ob_start() and ob_get_clean() are useful for buffering output of printed content and so forth, but I use them very rarely and tend to forget their order/syntax. So this post provides a quick copy/paste example that I can grab the next time I need to output buffer something.

It’s actually very simple:

ob_start(); // start output buffering
echo 'capture this output'; // whatever you want to capture
$output = ob_get_clean(); // get the captured content as a variable

That’s it. The cool thing about ob_get_clean() is that it executes both ob_get_contents() and ob_end_clean(). So you save a line or two of code. Here are references for the two functions required for basic output buffering:

★ Pro Tip:

USP ProSAC Pro