server sent events code example

Example 1: laravel server sent events

$loopTime = 1;
$response = new StreamedResponse(static function () use ($loopTime) {
    while (true) {
      	$data = [
        	'name' => 'Taylor Otwell'
        ]
      
      	echo "event: sse\n";
      	echo "data: " . json_encode($data) . "\n\n";
        echo str_pad('', 4096) . "\n";
      
    	ob_flush();
      	flush();
      	sleep($loopTime);

      	if (connection_aborted()) {
        	break;
      	}
    }
    ob_end_flush();
}
                                 
$response->headers->set('Content-Type', 'text/event-stream');
$response->headers->set('Cache-Control', 'no-cache');
return $response;

Example 2: php server sent events

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

while (true) {
  	$data = [
    	'name' => 'Rasmus Lerdorf'
    ]

  	echo "event: sse\n";
  	echo "data: " . json_encode($data) . "\n\n";
    echo str_pad('', 4096) . "\n";
      
	ob_flush();
  	flush();
  	sleep(1);

  	if (connection_aborted()) {
    	break;
  	}
}
ob_end_flush();

Tags:

Php Example