PHP进度条仅在脚本完成后显示

时间:2013-04-23 08:58:20

标签: php progress-bar

我正在尝试从http://w3shaman.com/article/php-progress-bar-script运行示例。

我在Windows上使用quickPHP。上面的教程有实时Demo链接,运行正常。

问题:

当我测试这个脚本时,只有当PHP完成处理时才会得到bar。我也尝试过使用jQuery UI进度条,但PHP在显示进度条之前很忙,然后在结束时突然显示100完成。有什么问题?

来自above link的代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>Progress Bar</title>
</head>
<body>
<!-- Progress bar holder -->
<div id="progress" style="width:500px;border:1px solid #ccc;"></div>
<!-- Progress information -->
<div id="information" style="width"></div>
<?php
// Total processes
$total = 10;

// Loop through process
for($i=1; $i<=$total; $i++){
    // Calculate the percentation
    $percent = intval($i/$total * 100)."%";

    // Javascript for updating the progress bar and information
    echo '<script language="javascript">
    document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd;\">&nbsp;</div>";
    document.getElementById("information").innerHTML="'.$i.' row(s) processed.";
    </script>';

    // This is for the buffer achieve the minimum size in order to flush data
    echo str_repeat(' ',1024*64);

    // Send output to browser immediately
    flush();

    // Sleep one second so we can see the delay
    sleep(1);
}

// Tell user that the process is completed
echo '<script language="javascript">document.getElementById("information").innerHTML="Process completed"</script>';
?>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

我想现在,QUick PHP不会让你得到如此处所述的中间结果:http://www.zachsaw.com/forum/viewtopic.php?f=11&t=27&hilit=flush(我知道这是一个旧帖子,但我找不到最近在QuickPHP上使用flush的任何引用)

似乎由于QuickPHP处理PHP输出的方式,它只在完成脚本完成执行时才发送结果。这就是为什么你要完成这个吧,因为你的脚本依赖于在php脚本仍在运行时继续向web浏览器发送数据的可能性。

所以答案是,现在不可能这样做。

答案 1 :(得分:0)

尝试使用这个:

//At the beginning of your PHP file
ob_start();
...

然后:

ob_flush();
flush();

而不是

flush();

答案 2 :(得分:0)

我的工作情况类似。我使用jquery,json来检查脚本执行的进度。 php脚本将临时文件写入其状态。我blogged关于它,这里可能有一些错误,但是工作做得很好。