浏览器结束PHP无限循环,然后打印数据

时间:2013-05-21 17:55:51

标签: php loops browser for-loop

我正在尝试从读卡器捕获实时源并使用PHP打印它。

<?php
    $i=0;
    for(;;)
    {
        $subdata=file_get_contents("/home/openflow/subscribedata.txt");
        $subdata2=file_get_contents("/home/openflow/subscribedatatemp.txt");

        if($subdata!=$subdata2)
        {
            copy("/home/openflow/subscribedatatemp.txt","/home/openflow/subscribedata.txt");
            $sub=file_get_contents("/home/openflow/subscribedata.txt");
            $i++;
            echo "\n". $i."--".$sub;
        }
    }
?>

我使用for循环作为无限循环。每当有新数据时,我的读卡器脚本会将其写入 subscribedatatemp.txt 文件,上面的脚本会检查 subscribedatatemp.txt (最新条目)和 subscribedata.txt (上一个条目)。如果存在差异,则应将最新版本复制到上一版本并回显最新数据。

问题是当我执行上面的PHP代码时,它暂时没有显示任何内容,并且在某个时候浏览器停止加载并显示它在加载时获得的所有数据。

这表示循环执行停止并且在while循环结束后正在打印所有数据,对吧?我怎么能纠正这个?

4 个答案:

答案 0 :(得分:0)

在代码顶部添加以下行:

set_time_limit(0);

所以你的整个代码看起来像这样:

<?php
set_time_limit(0);
$i=0;
for(;;)
{
$subdata=file_get_contents("/home/openflow/subscribedata.txt");
$subdata2=file_get_contents("/home/openflow/subscribedatatemp.txt");

if($subdata!=$subdata2)
{
copy("/home/openflow/subscribedatatemp.txt","/home/openflow/subscribedata.txt");
$sub=file_get_contents("/home/openflow/subscribedata.txt");
$i++;
echo "\n". $i."--".$sub;
}
}
?>

详情阅读set_time_limit() here

另外,请检查max_execution_time文件中的php.ini是否未设置。

答案 1 :(得分:0)

使用set_time_limit()通过在脚本开头传入0来使脚本无限期等,从而防止脚本超时。

您还希望在循环中添加sleep(),这样就不会占用所有CPU周期。

最后,您需要在每个循环结束时添加flush()以清空缓冲区并将其发送到客户端。

<?php
// set an infinite timeout
set_time_limit(0);
// create an infinite loop
while (true) {
    // do your logic here
    $subdata=file_get_contents("/home/openflow/subscribedata.txt");
    $subdata2=file_get_contents("/home/openflow/subscribedatatemp.txt");
    // .... etc.

    // flush buffer to the client
    flush();

    // go to sleep to give the CPU a break
    sleep(100);
}
?>

答案 2 :(得分:0)

如果我正确理解你,那你就是在每次循环后尝试显示输出(而不是等待整个脚本结束),所以要回显(flush)每个循环,你需要在循环结束时添加flush()

此外,我们将在循环之前添加set_time_limit(0),因此我们的脚本会花时间执行。

<?php
set_time_limit(0);
ob_end_flush();


$i=0;
for(;;)
{
$subdata=file_get_contents("/home/openflow/subscribedata.txt");
$subdata2=file_get_contents("/home/openflow/subscribedatatemp.txt");

if($subdata!=$subdata2)
{
copy("/home/openflow/subscribedatatemp.txt","/home/openflow/subscribedata.txt");
$sub=file_get_contents("/home/openflow/subscribedata.txt");
$i++;
echo "\n". $i."--".$sub;
/*flush()*/
}

}
ob_start();
?>

答案 3 :(得分:0)

在循环结束时使用flushsleep函数...

但最好使用ajax调用..