Write To The Output Buffer In PHP

10th February 2009 - 2 minutes read time

The first thing you learn about in PHP is probably how to print something. This is usually done with a call to the echo or print, but there is another way to print things by writing content directly to the output buffer. The following code looks like you are writing to a file, but the text will appear in the browser window because we are writing to the php://output output stream.

  1. $fp = fopen("php://output", 'r+');
  2. fputs($fp, "Hello World");

Or another way...

file_put_contents("php://output", "Hello World");

The php://output stream is an encapsulation between PHP and the browser. The stream doesn't really exist, but PHP knows what to do with it.

Why would you ever need to know this? Well lets say that you had an application that produced some logs when users performed certain actions. You might want to print those to screen in your development environment rather than save them. So rather than altering the code to see what environment you are in you can just set a configuration option so that you write to php://output instead of the log file. This means that your logs will appear with your output.

Comments

Permalink
thanks for the code, very useful for me.

Super 7 Lotto (Tue, 02/17/2009 - 17:33)

Add new comment

The content of this field is kept private and will not be shown publicly.