PHP – Using Output Buffering

A common example of this is if you have a function or a script that echo’s out a string, but you are using the code in that instance where you don’t want it to print to the screen at that point (when using a template system or framework system, for example).

In this case you would still want to be able to re-use the code, but just prevent anything from being printed out at that exact point.

Let’s  look at this example:


echo 'Hello World!!!';
$getContent = ob_get_contents();


// Do some actions

// Print the stored content (only if you want)...
echo 'Now: ' . $getContent;

You probably were familiar with at least some of these, but I’m hoping that someone will find this list useful in some capacity.Other functions that can also be usefull:

 ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() 

Leave a Reply

Your email address will not be published. Required fields are marked *