42

What's the difference between ob_clean() and ob_flush()?

Also what's the difference between ob_end_clean() and ob_end_flush()? I know ob_get_clean() and ob_get_flush() both get the contents and end output buffering.

Adam Wagner
  • 15,469
  • 7
  • 52
  • 66
Alex V
  • 18,176
  • 5
  • 36
  • 35
  • See the manual pages on [`ob_clean()`](http://php.net/ob_clean) and [`ob_flush()`](http://php.net/ob_flush) and [`ob_end_clean()`](http://php.net/ob_end_clean) and [`ob_end_flush()`](http://php.net/ob_end_flush) or explain which specific aspect needs elaboration. – mario Jan 07 '12 at 15:55
  • 3
    Everything you need to know is in the documentation: http://php.net/manual/en/ref.outcontrol.php – dev-null-dweller Jan 07 '12 at 15:55
  • I've been studying them, it doesn't look like there is a difference. Even in the examples. – Alex V Jan 07 '12 at 16:05
  • @AlexV I've updated my answer... but basically these functions write directly to the output-buffer (just like `print` or `echo`), therefore you will see no difference in the function signatures. – Adam Wagner Jan 07 '12 at 16:51

2 Answers2

62

the *_clean variants just empty the buffer, whereas *_flush functions print what is in the buffer (send the contents to the output buffer).

Example:

ob_start();
print "foo";      // This never prints because ob_end_clean just empties
ob_end_clean();   //    the buffer and never prints or returns anything.

ob_start();
print "bar";      // This IS printed, but just not right here.
ob_end_flush();   // It's printed here, because ob_end_flush "prints" what's in
                  // the buffer, rather than returning it
                  //     (unlike the ob_get_* functions)
Adam Wagner
  • 15,469
  • 7
  • 52
  • 66
3

The key difference is *_clean() discards changes and *_flush() outputs to the browser.

Usage of ob_end_clean()

it is mostly used when you want to have a chunk of html and do not want to output to the browser right away but may be used in future.

Eg.

ob_start()
echo "<some html chunk>";
$htmlIntermediateData = ob_get_contents();
ob_end_clean();

{{some more business logic}}

ob_start();
echo "<some html chunk>";
$someMoreCode = ob_get_content();
ob_end_clean();

renderTogether($htmlIntermediateCode, $someMoreCode);

where as ob_end_flush() will render twice, once for each.

Arun Gangula
  • 143
  • 1
  • 9