Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP immediate echo

Tags:

php

io

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.

like image 488
Tom Avatar asked Apr 06 '09 01:04

Tom


3 Answers

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().

like image 122
ieure Avatar answered Sep 25 '22 07:09

ieure


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.

like image 32
Jeremy Stanley Avatar answered Sep 23 '22 07:09

Jeremy Stanley


Yes, padding your output to 1024 bytes will cause most browsers to start displaying the content.

But we also learn from @nobody's answer to question "How to flush output after each `echo` call?" that the 1024 bytes browser buffering effect only happens when the browser has to guess the character encoding of the page, which can be prevented by sending the proper Content-Type header (eg. "Content-Type: text/html; charset=utf-8"), or by specifying the content charset through appropriate html meta tags. And it worked as well for me in all browsers.

So basically, all one need to do is:

header('Content-Type: text/html; charset=utf-8');
ob_implicit_flush(true);

With no requirement for extra padding or flushing, which is of great cosmetic benefit for the code! Of course, headers have to be sent before any content, and one also has to make sure no output buffering is going on.

Problem definitely solved for me! Please (+1) @nobody's answer on the other question as well if it works for you. If, although, one still encounters problems, I suggest checking out the answers to that other question for other specific situations that might presumely prevent implicit flushing from working correctly.

like image 38
Bigue Nique Avatar answered Sep 21 '22 07:09

Bigue Nique