htmx Server Sent Events

sse.php

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

$time = date('r');
$result =  "La hora en el servidor es: {$time}";
echo "data: " . json_encode($result) . "\n\n";
ob_end_flush();
flush();

  // Break the loop if the client aborted the connection (closed the page)

if (connection_aborted()) break;?>

En este ejemplo especificamos message, de ahí que la salida de php solo muestre data. En la cabecera devuelta lo que se espera es de tipo text/event-stream.

<div hx-ext="sse" sse-connect="sse.php" sse-swap="message"></div>

Debido a que a partir de la versión 1.8 se usa como una extensión, se ha de añadir la llamada a la extensión

<script src="https://unpkg.com/htmx.org@1.8.0"></script>
<script src="https://unpkg.com/htmx.org@1.8.0/dist/ext/sse.js"></script>

Otro caso es en el que queramos obtener un mensaje en concreto:

<div 
    hx-ext="sse" 
    sse-connect="time.php" 
    sse-swap="eventFecha" 
    hx-target="#result"
>

time.php

<?php
date_default_timezone_set("Atlantic/Canary");
header("Cache-Control: no-store");
header("Content-Type: text/event-stream");

$counter = rand(1, 10);
while (true) {
  // Every second, send a "ping" event.

  echo "event: eventFecha\n";
  $curDate = date('d \d\e m \d\e Y H:i:s');
  echo 'data: {"time": "' . $curDate . '"}';
  echo "\n\n";

  // Send a simple message at random intervals.

  $counter--;

  if (!$counter) {
    echo 'data: This is a message at time ' . $curDate . "\n\n";
    $counter = rand(1, 10);
  }

  ob_end_flush();
  flush();

  // Break the loop if the client aborted the connection (closed the page)

  if (connection_aborted()) break;

  sleep(1);
}
?>

Publicado

en

por

Etiquetas: