Say I have the following:
for ($i = 0; $i < 10; $i++) {
echo $i;
sleep(1);
}
Now, this will display:
0123456789
However, it will take 9 seconds to load, and will not display real-time. How would I display it so it would be:
0(1 second)2(1 second)3(...)
My second question involves overwriting the current data on the page. For example, say I have the same code as above. However, I want to display each number as itself. So the page would be:
0
Then after 1 second
1
And so on.
for ($i = 0; $i < 10; $i++) {
echo $i."
";
$timeFirst = strtotime(date());
sleep(1);
$timeSecond = strtotime(date());
echo ($timeSecond - $timeFirst)." second(s)
";
}
You can only do it with Client side script such as javascript. DOM
loads only after the complete execution of your server side script.
There is no way you can execute each command and render the output to the web browser, unless you are doing it at CLI or doing it via Client Side.
Try this
for ($i = 0; $i < 10; $i++) {
echo $i;
flush();
ob_end_flush();
sleep(1);
}