【问题标题】:php issue with while and sleep , the while loop echo all only at the end of the loopphp 的 while 和 sleep 问题,while 循环仅在循环结束时回显
【发布时间】:2016-01-21 14:18:05
【问题描述】:

我有一个关于 while 和 sleep 的 php 问题,while 循环仅在循环结束时回显,每 1 秒回显一次

我试过了:

<?php
ob_implicit_flush(true);
ob_end_flush();


$i=0;
while($i<=5) {
     echo $i;
     sleep(1);
     flush();
     $i++;
}
?>

【问题讨论】:

  • 我刚刚运行了该代码,它每秒都会在列表中添加一个数字。那我是不是误解了这个问题?
  • 它加载页面 5 秒并一次回显所有五个数字
  • @bill 但是如果你在 CLI 中运行,你会看到其他的每个数字。
  • 什么是 CLI 我用谷歌搜索了它,但什么也没找到
  • CLI 意味着使用命令控制台运行 PHP 脚本,而不是在 web 服务器中将它们作为页面运行

标签: php loops while-loop sleep


【解决方案1】:

试试这个。它在我的浏览器上工作

<?php
ini_set('zlib.output_compression','Off');// if not in php.ini
header( 'Content-type: text/html; charset=utf-8' );
header("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
ob_implicit_flush(true);
ob_end_flush();
$i=0;
while($i<=5) {
     echo $i;
     flush();
     sleep(1);
     $i++;
}
?>

确保 php.ini 中的这个值 zlib.output_compression=Off

另请参阅此question 中的所有答案以获取详细答案

【讨论】:

  • 如果更改了 php.ini 中的上述值,是否重新启动 apache 服务器。我最后检查了它每秒显示的每个数字
  • 我把值放在 php.ini 文件中,在同一个文件夹中我需要更改页面的权限,如果是,应该是什么权限号?
  • 尝试使用终端以root权限编辑文件。请勿更改其权限,否则可能会导致其他问题。
  • 不要将 zlib.output_compression 添加为新条目。在 php.ini 中搜索,如果它已经存在,则将其值更新为 Off,否则将其添加为新
  • 那么你将如何运行 php man 。如果你不知道怎么做,最好重启你的机器
【解决方案2】:
if (!ob_get_level()) {
    ob_start();
} else {
    ob_end_clean();
    ob_start();
}

$i = 0;
while ($i <= 5) {
    flush();
    ob_flush();
    echo $i . "\n";
    $i++;
    sleep(1);
}

此代码将从刷新所有回声开始,然后开始逐个输出回声。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多