How can PHP scripts with delayed output be optimized for live messaging during execution?

When dealing with PHP scripts that have delayed output, it is important to optimize them for live messaging during execution to provide real-time updates to users. One way to achieve this is by using output buffering to capture the output and send it to the client incrementally as it becomes available. This can help improve the user experience by displaying messages as they are generated, rather than waiting for the entire script to finish executing.

<?php

ob_start();

// Perform time-consuming tasks here
for ($i = 0; $i < 10; $i++) {
    echo "Processing item $i...<br>";
    ob_flush();
    flush();
    sleep(1); // Simulate a delay
}

ob_end_flush();

?>