The Output Buffer (ob_start())

Custom output buffer

Working with the output buffer begins with a function ob_start()– this function has three optional parameters, but I’ll talk about them a little later, but for now, remember – to enable the output buffer, we use the function ob_start():

ob_start();
echo "hello world";
If we need to save the data or otherwise process the output, we’ll need the function ob_get_contents(). After saving the data, we can clear and disable the buffer—for this, we’ll use the function ob_end_clean(). Putting it all together, we get the following code:

ob_start();
echo "hello world";
$content = ob_get_contents();
ob_end_clean();

The function ob_get_contents()can be called multiple times, but I haven't encountered this in practice:

ob_start();
echo "hello ";
$a = ob_get_contents();
echo "world ";
$b = ob_get_contents();

We’ve cleared things up a bit—we now have information on how to enable the buffer, how to retrieve data from it, and how to disable it. What other interesting things can you do with it? There’s practically nothing you can do with it—you can send it (flush it) to the browser (the “flush” keyword), clear it (clean), or disable it (end). And you can combine all of these things together, too.

  • ob_clean()— we read the function name as “clear the output buffer”
  • ob_flush()— “sending the output buffer”
  • ob_end_clean()— “disable and clear the output buffer”
  • ob_end_flush()— “We disable the output buffer and send it to the browser.”
  • ob_get_clean()— “we get the output buffer, clear it and disable it” — there’s a small deviation from the rule here, this function should be called like ob_get_end_clean(), but they decided to simplify it and threw it outend
  • ob_get_flush()— “we send the output buffer, clear it and disable it,”ob_get_end_flush()