为什么此PHP代码(comet)不起作用?
问题描述:
set_time_limit(0);
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
flush();
while($i < 10)
{
sleep(1);
$i++;
echo $i;
flush();
}
为什么我的代码没有打印出1,然后等待并打印2,然后等待并打印3.相反,它只等待10秒并一次打印出12345678910吗?
Why doesn't my code print out 1, then wait and print 2 then wait and print 3. Instead, it just waits 10 seconds and prints out 12345678910 all at once?
有没有一种方法可以按我的需要将其打印成大块?
Is there a way to print it in chunks as I want?
答
可能是因为输出缓冲。尝试将其添加到文件顶部以关闭所有打开的缓冲区:
It's likely because of output buffering. Try adding this at the top of the file to close all the open buffers:
while(ob_get_level() > 0) {
ob_end_flush();
}
您还可以添加 ob_flush()$代码中
flush()
命令后的c $ c>:
You can also add ob_flush()
after the flush()
command in your code:
$i++;
echo $i;
flush();
ob_flush();
(请注意,您只需要做一个,而不是两个,但都可以尝试)。 ..
(Note that you should only have to do one of them, not both, but try it)...