why ob_start() and ob_get_clean() are so important

Basically ob_start() create buffer so that without using echo again and again we can get all html in the variable ob_get_clean()

ob_get_clean() does 3 things for us in a single call function. It goes as follows:

  • Fetch buffered content.
  • Clean buffered content
  • Shut off buffering.

For example

We can write code snippet like below

 

$output = '';
$output .= '<h1>Dummy</h1>';
if(true === $c ){ //here c is some condition.
$output . = '<div>In loop</div>';
}
$output .= '<div>End</div>';
echo $output;

But when talk to good coding then it is not good practice. By page performance it is also not good. So in place concat output must use ob_start() and ob_get_clean()

For example above code can we written as :

<?php ob_start(); ?>
<h1>Dummy</h1>
<?php if ( true === $c ) { ?>
<div>In loop</div>
<?php } ?>
<div>End</div>
<?php
$output = ob_get_clean();
echo $output;

You can check out my plugin code on git where i use buffer in application.

https://github.com/sandeepjain2015/covid19_statistics/blob/master/class-covid19.php

Leave a Reply

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