views:

713

answers:

5
+2  Q: 

PHP immediate echo

I have quite a long data mining script, and in parts of it I echo some information to the page (during a foreach loop, actually.)

However I am noticing that the information is being sent to the browse not immediately as I had hoped, but in 'segments'.

Is there some function I can use after my echo to send all the data to the browser immediately?

Thanks.

+8  A: 

You probably want flush(). However, PHP may be using output buffering. There are a few ways that this can change things, but in a nutshell, you can flush(), then ob_flush().

ieure
doh, a minute before mine. Good on the ob_flush() though, +1
Jeremy Stanley
@Jeremy - I gave ya an up vote to make up for it :)
Tim
+4  A: 

You can try using flush() after each echo, but even that won't guarantee a write to the client depending on the web server you're running.

Jeremy Stanley
+2  A: 

You should be able to use something like this to force output to be sent immeadiately. Put it at the part of the code you want the output to be sent.

flush();
ob_flush();
Luke
A: 

Note also that some browsers won't start displaying anything until the body of the response contains a certain amount of data - like 256 or 1024 bytes. I have seen applications before that pad data with a 1024 character long comment near the top of the page, before they do a flush. It's a bit of a hack, but necessary.

This applies to Internet Explorer and Safari IIRC.

So,

  • If it is the first flush, make sure you have output at least 1024 bytes sofar (not including HTTP headers).
  • Call flush()
  • If you can determine that there is output buffering in place, issue ob_flush()

I like to just use

while (ob_get_level()) ob_end_flush();

near the start of my script somewhere, and then just

flush();

whenever I want to flush. This assumes that you don't want any output buffering at all, even if it was set up before your script (such as in a PHP.ini or htaccess configuration).

thomasrutter
A: 

To perfectly work this out in Google chrome, try this:

$i = 0;
$padstr = str_pad("",512," ");
echo $padstr;

while ($i < =4){
    $padstr = str_pad("",512," ");
    echo $padstr;
    echo "boysmakesh <BR> ";
     flush();
    sleep(2);
    $i = $i + 1;
}

Ee are sending 512 bytes before sending EACH echo. Don't forget to put <BR> at the end of content before you flush. Else it won't work in Chrome but works in IE.

The data we padding is browser dependent. For some browsers it's enough to have 256 bytes but some need 1024 bytes. For chrome it is 512.

boysmakesh