PHP output text before sleep

2019-01-15 15:13发布

问题:

I want PHP to output some text, then sleep for a second and a half, and then output some more text.

<?php

echo 'Output one.';

usleep(1500000);

echo 'Output two.';

?>

My problem is that all text is being put out simultaneously - after having waited those 1.5 seconds. I have read something about a function called flush - but it doesn't seem to work. Maybe I'm not using it write. Any help would be appreciated ^^

Thanks in advance!

回答1:

check this out

<?php

ob_start();

echo 'Output one.';
ob_flush();
usleep(1500000);
echo 'Output two.';
ob_flush();

?>


回答2:

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.



回答3:

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.



回答4:

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.



回答5:

echo 'Output one.';
ob_flush(); 
flush();
usleep(1500000);
echo 'Output two.';


回答6:

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>



标签: php text sleep