Search code examples
phpjsonechoserver-sent-events

two seemingly identical PHP echo blocks, one doesn't work?


I have two seemingly identical chunks of code. With the first one, the client-side file (using a Server Sent Event connection) can properly receive and display JSON data, while with the other code it can't. I can't for the life of me figure out why.

Here's the first, working code:

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

function sendMsg($id , $msg) {
  echo "id: $id" . PHP_EOL;
  echo "data: {\n";
  echo "data: \"name\": \"Bob\", \n";
  echo "data: \"msg\": \"$msg\", \n";
  echo "data: \"id\": $id\n";
  echo "data: }\n";
  echo PHP_EOL;
  ob_flush();
  flush();
}

sendMsg(1, 'hello');

In the client-side file, data.name will display "Bob" and data.msg will display "hello".

This is the non-working code:

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

$out .= "id: 1" . PHP_EOL;
$out .= "data: {\n";
$out .= "data: \"name\": \"Bob\",\n";
$out .= "data: \"msg\": \"hello\", \n";
$out .= "data: }\n";
$out .= PHP_EOL;
echo $out;
ob_flush();
flush();

It seems exactly the same to me but nothing will display! What gives? I've even tried translating the non-working code to use all "echo" statements, instead of .out =, so that it was near-identical to the first.... does anyone see an error/difference?

Thanks for any help!


Solution

  • In your second example, the JSON string you are sending out has a dangling comma at the end of it, which isn't valid.

    You're sending:

    {
        "name": "Bob",
        "msg": "hello",
    }                 ^---Right there