PHP code example of igorw / event-source

1. Go to this page and download the library: Download igorw/event-source library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

igorw / event-source example snippets






use Igorw\EventSource\Stream;

foreach (Stream::getHeaders() as $name => $value) {
    header("$name: $value");
}



use Igorw\EventSource\Stream;

$stream = new Stream();

while (true) {
    $stream
        ->event()
            ->setData("Hello World")
        ->end()
        ->flush();
    
    sleep(2);
}



$lastId = filter_input(INPUT_SERVER, 'HTTP_LAST_EVENT_ID');

if ($lastId) {
    $buffer = getMessagesAfter($lastId);

    foreach ($buffer as $message) {
        $stream->event()
            ->setId($message['id'])
            ->setData($message['data']);
    }

    $stream->flush();
}



$stream
    ->event()
        ->setEvent('foo')
        ->setData($message['data']);
    ->end()
    ->event()
        ->setEvent('bar')
        ->setData($message['data']);
    ->end()
    ->flush();



$data = array('userIds' => array(21, 43, 127));

$stream
    ->event()
        ->setData(json_encode($data));
    ->end()
    ->flush();



$handler = function ($chunk) {
    echo $chunk;
    ob_flush();
    flush();
};



$stream = new Stream($handler);


set_time_limit(0);