Search code examples
phpdrupal-7

ob_start() unexpected behaviour in drupal 7


I have written below code in drupal custom module.

I am getting output in $html but it still printing the output of file. ie: if string "hello" is there in custom-report.php it prints it twice.

ob_start();
require_once('templates\custom-report.php');
$html = ob_get_contents();
echo $html;

Solution

  • Use ob_get_clean() instead of ob_get_contents()

    You must clean and close your output buffer.


    The following will:

    1.) Save the contents 2.) Output them only when you need them.

    ob_start();
    require_once('templates\custom-report.php');
    $html = ob_get_clean();
    echo $html;
    

    ob_get_contents()

    This will return the buffer contents but does not erase the output from the buffer.


    ob_get_clean()

    This will return the buffer contents, clean the output buffer, and end output buffering.


    The code from your question has this undesired effect:

    1.) Output buffer is saved but left open. 2.) echo $html sends your saved copy of the output buffer contents. 3.) PHP automatically flushes open output buffer contents when it reaches the end of a script. So your output is sent a second time.


    This is a fantastic resource for Output Buffer questions: http://www.tuxradar.com/practicalphp/13/3/0