Skip to content
PHP Logo

What are the benefits of using ob_start() and ob_flush() functions to control output in PHP?

When working with PHP, sometimes you may need to control the output that is sent to the browser. This can be achieved using the ob_start() and ob_flush() functions. ob_start() allows you to buffer the output, meaning that it is stored in memory rather than immediately sent to the browser. This can be useful for situations where you need to modify the output before it is displayed. ob_flush() then sends the buffered output to the browser.

php
<?php

// Start output buffering
ob_start();

// Output some content
echo "Hello, World!";

// Get the buffered output
$output = ob_get_contents();

// Modify the output if needed
$output = str_replace("World", "PHP", $output);

// Flush the modified output to the browser
ob_end_clean();
echo $output;

?>