Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing results immediately (php)

Tags:

php

I have a php script that connects 10 different servers to get data. I want it to print the results of the 1st connection before the second one begins.

like image 976
melih Avatar asked Sep 01 '09 17:09

melih


People also ask

How print all form data in PHP?

Simply add echo "<pre>"; before the var_dump() or print_r().

What is difference between echo and print?

echo and print are more or less the same. They are both used to output data to the screen. The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument.

How do I print a PHP script?

The echo command is used in PHP to print any value to the HTML document. Use <script> tag inside echo command to print to the console.

What is command for print in PHP?

The print() function outputs one or more strings. Note: The print() function is not actually a function, so you are not required to use parentheses with it. Tip: The print() function is slightly slower than echo().


1 Answers

Using flush and/or ob_flush, you should get what you want.

Here is a quick demonstration :

for ($i=0 ; $i<10 ; $i++) {
    echo "$i<br />";
    ob_flush();
    flush();
    sleep(1);
}

Each second, a number will be sent to the browser, without waiting for the loop/script to end.
(Without both flush and ob_flush, it waits until the end of the script to send the output)


Explanation about why you need both, quoting from the flush page in the manual :

Flushes the write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats.

flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.


If this doesn't work for you, taking a look at the comments on the two pages of the manual can give you a couple of pointers on "why it could fail"

like image 109
Pascal MARTIN Avatar answered Sep 17 '22 19:09

Pascal MARTIN