ob_get_contents + ob_end_clean vs ob_get_clean

To answer your question:

ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean().

Yes. It is functionally equivalent.


Case 1:

ob_get_contents() + ob_end_clean():

ob_get_contents — Return the contents of the output buffer

ob_end_clean — Clean (erase) the output buffer and turn off output buffering

So, basically, you're storing the contents of the output buffer to a variable and then clearing it with ob_end_clean().

Case 2:

ob_get_clean — Get current buffer contents and delete current output buffer

You're storing the buffer contents to a variable and then the output buffer is deleted.


What you're doing is essentially the same. So, I don't see anything wrong with using the second code-block here, since they're both doing the same thing.


ob_get_contents() can be used to continue the output buffering.

Example:

ob_start();
echo 'Something!';
$html1 = ob_get_contents();
echo 'More to say!';
$html2 = ob_get_contents();
ob_end_clean();

At the end the vars have this content:

$html1 = 'Something!';
$html2 = 'Something!More to say!';

There is one teeny difference between

$stuff = ob_get_clean();

and

$stuff = ob_get_contents();
ob_end_clean();

which is that the latter will throw an E_NOTICE if there is no active output buffer at the time that you call it, and the former won't. Throwing the notice actually seems like the saner behaviour to me, since if you're calling these functions without an output buffer then you're probably doing something wrong!

That the two approaches are pretty much equivalent is explicitly documented on php.net, which says:

ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean().

The warning-throwing behaviour of ob_end_clean is also documented:

If the function fails it generates an E_NOTICE.

Note that there is no similar sentence in the docs of ob_get_contents or ob_end_clean.

If you really want to assure yourself there are no further differences between these functions (there aren't), you can dive into the definitions of ob_get_contents, ob_end_clean and ob_get_clean in the source. There's some weird error handling for impossible cases in ob_get_clean that should never get reached, but besides that, you can see that the behaviours are as described.


Based on the documentation,

ob_get_contents() + ob_end_clean()

is supposed to work the same as:

ob_get_clean()

However, because of a bug in PHP, it doesn't. Roland from nextendweb filed a bug report:

https://bugs.php.net/bug.php?id=76563

If you use ob_start with callback, the callback does not run, if you use ob_get_clean() on the same output buffer. The callback get skipped, which gives unexpected results. I think it is a bug.

So, if you're passing a callback to ob_start(), you'll need to use

$content = ob_get_contents();
ob_clean();

instead of:

$content = ob_get_clean();

Testing on sandbox, you will notice that it affects all PHP versions.

Tags:

Php