If you output some html or javascript code or use echo or print within php, this information is being sent to the browser. If you use the output buffer this information is first stored on the server until either the script has finished executing or you performed some kind of action on the buffer.
We will now look at how to use the output buffer and what we can do with it.
You have to start the output buffer before anything is sent to the browser. So one of the ways to ensure that is starting it right after you opened the php tag.
Example:
Make sure that there is really nothing before the php opening tag. Even a space can cause errors.
If at any time you wish to send the content of the buffer to the browser you can do this with the following line.
After this point however the output buffer will continue to buffer the content which is send to the browser. If you which to simply send the content of the buffer and stop using it you can do this with the following code.
In some instances you might wish to delete whatever is stored in the output buffer and build up a new page. You can do this by using the following command.
Just like the ob_flush(); command, the output buffer would continue buffering the content which is sent to the browser. The command to delete the buffer and stop it is
If you started the output buffer you can get the content of it at any time (unless you have deleted it or sent it to the browser of course). This is done by the following line
This means that everything you echo or would be sent otherwise to the browser between this line and the ob_start(); will now be in $var.
Now you may wonder what you can do with this. Well there are multiple things. You could create a templating system for example. You could create a file in which you have all the look and feel but without content. Where you would usually place content like in the title or a menu you would place tokens.
Example:
So in the above example we have 3 placeholders. one for the title, menu and for content. And this is the way we can use the template with the output buffer.
As you can see once you have the content you can do whatever you wish with it. Here are some ideas what you could do:
Enjoy playing with the output buffer.