PHP provides a series of functions that allow you to capture any output that should be sent to the browser so you can do something else with it (or ignore it). In this article, we’ll go over a couple use cases for how you can use PHP’s output buffering.
Starting Output Buffering
ob_start() function starts PHP’s output buffering. As soon as you call this function all output will be stored in an internal buffer and nothing will be sent to the browser until the script ends or you do something with the buffer.
Clearing All Previous Output
The first function I’m going to cover is
ob_end_clean(). This function discards the contents of the output buffer and turns output buffering off:
Notice that “Hello All!” wasn’t printed because we cleaned the output buffer it was sent to.
You might use this setup to run a function that produces output and returns a value but you don’t want to use it’s output (a better solutions is to extract this logic but I know that’s not always possible).
Saving Output to a String
The next function is
ob_get_contents() which is used to retrieve the contents of the output buffer.
Notice that “Hello All!” has the “string(10)” in front of it which indicates it was displayed using
var_dump() and not
This is super helpful if you want to cache the generation of a section of a page and then reuse it later. I love doing this for menus that are dynamically generated but don’t change during a login because it can save some time when the menu queries the database or accesses an external endpoint.
PHP also has an
ob_get_clean() function which performs the
ob_clean() functions at the same time:
Finally, I thought it would be helpful to see what happens if you don’t
ob_end_clean() after you get the contents:
Notice that it output “Hello All!” twice.
Multiple Output Buffers
The last thing I want to talk about is how you can stack output buffers. Each time you call
ob_start() PHP creates a new output buffer. When you do this you’ll need to make sure you call an
ob_end_*() function for each
This is just an overview of PHP’s output buffering functions. If we missed something or this has been helpful to you let us know in the comments.