PHP Output Buffering Basic usage getting content between buffers and clearing


Output buffering allows you to store any textual content (Text, HTML) in a variable and send to the browser as one piece at the end of your script. By default, php sends your content as it interprets it.


// Turn on output buffering

// Print some output to the buffer (via php)
print 'Hello ';

// You can also `step out` of PHP
// Return the buffer AND clear it
$content = ob_get_clean();

// Return our buffer and then clear it
# $content = ob_get_contents();
# $did_clear_buffer = ob_end_clean();


#> "Hello <em>World</em>"

Any content outputted between ob_start() and ob_get_clean() will be captured and placed into the variable $content.

Calling ob_get_clean() triggers both ob_get_contents() and ob_end_clean().