两个看似相同的PHP echo块,一个没有';不行?
我有两段看起来完全相同的代码。对于第一个,客户端文件(使用服务器发送的事件连接)可以正确地接收和显示JSON数据,而对于其他代码则不能。我一辈子都不知道为什么 这是第一个工作代码:两个看似相同的PHP echo块,一个没有';不行?,php,json,echo,server-sent-events,Php,Json,Echo,Server Sent Events,我有两段看起来完全相同的代码。对于第一个,客户端文件(使用服务器发送的事件连接)可以正确地接收和显示JSON数据,而对于其他代码则不能。我一辈子都不知道为什么 这是第一个工作代码: header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); function sendMsg($id , $msg) { echo "id: $id" . PHP_EOL; echo "data: {\n";
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');
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();
在客户端文件中,data.name将显示“Bob”,data.msg将显示“hello”
这是非工作代码:
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');
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();
对我来说似乎完全一样,但什么都不会显示!有什么好处?我甚至尝试将不工作的代码翻译为使用所有“echo”语句,而不是.out=
,这样它与第一个几乎相同。。。。有人看到错误/差异吗
谢谢你的帮助 在第二个示例中,发送的JSON字符串末尾有一个悬空逗号,这是无效的 您正在发送:
{
"name": "Bob",
"msg": "hello",
} ^---Right there
在第二个示例中,发送的JSON字符串末尾有一个悬空逗号,这是无效的 您正在发送:
{
"name": "Bob",
"msg": "hello",
} ^---Right there
您忘记初始化
$out=''代码>在开头。检查是否收到PHP警告?这些警告如何相同?不管怎样,PHP错误日志显示的是非工作变量的什么?$out
-变量未初始化。是的,我强烈建议使用“json\u econde”。如果你手工编写json对象代码,你总是很容易弄乱。这将是一场噩梦,因为阵列更容易实现。您还可以使用json_encode对对象进行编码代码>在开头。检查是否收到PHP警告?这些警告如何相同?不管怎样,PHP错误日志显示的是非工作变量的什么?$out
-变量未初始化。是的,我强烈建议使用“json\u econde”。如果你手工编写json对象代码,你总是很容易弄乱。这将是一场噩梦,因为阵列更容易实现。您还可以使用json_encode对对象进行编码。