How can PHP be used to display data while a script is running?

When a PHP script is running, it typically processes all its tasks before displaying any output to the user. However, you can use output buffering and the flush() function to display data to the user while the script is still running. This can be useful for showing progress bars, status updates, or any other real-time information.

<?php

// Turn on output buffering
ob_start();

// Your long-running script
for ($i = 1; $i <= 10; $i++) {
    echo "Processing step $i...<br>";
    flush();
    sleep(1); // Simulate some processing time
}

// Clear the output buffer
ob_end_flush();

?>