How can Server-Sent-Events be utilized to efficiently pass data from a PHP script to JavaScript in real-time?

Server-Sent-Events can be utilized to efficiently pass data from a PHP script to JavaScript in real-time by establishing a persistent connection between the server and the client. This allows the server to send updates to the client whenever new data is available, without the need for the client to constantly poll the server for updates.

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

// Simulate data updates
for ($i = 0; $i < 10; $i++) {
    echo "data: " . $i . "\n\n";
    ob_flush();
    flush();
    sleep(1); // Simulate data update every 1 second
}
?>