I want PHP to output some text, then sleep for a second and a half, and then output some more text.
While Pentium10's solution will probably work, you might want to consider moving this to the client side. Have an async call to get the first value, print it, sleep for the required amount of time and then repeat for the second value.
check this out
<?php
ob_start();
echo 'Output one.';
ob_flush();
usleep(1500000);
echo 'Output two.';
ob_flush();
?>
echo 'Output one.';
ob_flush();
flush();
usleep(1500000);
echo 'Output two.';
Your problem is that this is PHP. It's a pre-processor. So the php script runs, outputs the first log, then sleeps, then outputs the second log, and only thén it's sent to and shown in your browser.
You need javascript if you want the delay to be visible on your browser screen.
function showLog () {
$(".secondlog").show();
}
$(document).ready(function() {
setTimeout(showLog,3000);
});
.firstlog {
border: 1px solid #AEAEAE;
}
.secondlog {
display: none;
border: 1px solid #AEAEAE;
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="firstlog">
Output of first log
</div>
<div class="secondlog">
Output of second log
</div>
<p>Wait for 3 seconds...</p>
Pentium10's answer did not quite work for me.. However when I went to the PHP documentation page, there were a lot of good comments on there.
http://php.net/manual/en/function.ob-flush.php
This worked for me using Firefox 3.5.9, PHP 5.2.11, Apache running off local Windows 7 laptop:
echo "test";
ob_end_flush();
flush();
usleep(x);
echo "test";
The ob_end_flush() was crucial to getting data sent.
I think it is more a http request/response issue. On the command line your script works fine.
Normally the response is prepared completely and send to the client. If your response has such a size that multiple tcp packages have to be send, it could happen that the first packages are send, before you script is ready with processing. So it depends on the size of the output. Depending on the client/web browser, it could also happen that the first packages get rendered, before the complete response arrives at the client.
As Noufal Ibrahim answered while im typing, I totally agree with him. Do it in a asynchrone manner.