Question

I've written a PHP script that makes a request to a search engine, accesses the served results, extracts some details from the results and then prints them in a more useful form.

It all works well, but something I've discovered by accident is that calling echo or print while waiting for data to be streamed in can result in the output being streamed as well. Specifically, there are multiple pages of results, so I access the first page, read in and re-print the content, then move on to the next page, and while waiting for that next page to load, the previous page's content becomes visible in the browser.

What I don't understand is why this happens so inconsistently. Sometimes exactly one page will be printed before moving onto the next page, sometimes less and sometimes more. Then when I do basically the same thing afterwards (read in the page each result points to), the output is barely streamed at all, being redrawn every minute or so.

I'm using file_get_contents($url) to retrieve the content, and calling a function with an echo in it to print what has been loaded so far. Is this streaming print behaviour a feature of the browser and independent of what I write in PHP? If not, how can it be controlled better?

Was it helpful?

Solution

The easiest fix is to use output buffering. The basic idea is to call ob_start() at the beginning of your script and then call ob_end_flush() when you want the pages content to be sent to the client. Doing this will save all of your output until you want your program to send it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top