What is output buffering in PHP

Output buffering in PHP is a feature that allows you to control the output of your script before sending it to the browser. This means you can capture the output produced by your PHP code and manipulate it, delay it, or even discard it. It's particularly useful for modifying headers or performing graceful error handling.

How Output Buffering Works

When output buffering is turned on, any output generated by PHP is not sent to the browser immediately. Instead, it is stored in an internal buffer. You can then use functions like ob_start() to start buffering, ob_get_contents() to retrieve the contents of the buffer, and ob_end_flush() to send the contents to the browser.

Example of Output Buffering


Hello, World!";
echo "This is an example of output buffering in PHP.";

// Get the contents of the buffer
$output = ob_get_contents();

// Clean (erase) the output buffer and end it
ob_end_clean();

// You can manipulate the output if needed
$output = str_replace("Hello", "Hi", $output);

// Send the modified output to the browser
echo $output;
?>
    

PHP Output Buffering Web Development PHP Functions