8.12. Buffering Output to the Browser

Problem

You want to start generating output before you’re finished sending headers or cookies.

Solution

Call ob_start( ) at the top of your page and ob_end_flush( ) at the bottom. You can then intermix commands that generate output and commands that send headers. The output won’t be sent until ob_end_flush( ) is called:

<?php ob_start(); ?>

I haven't decided if I want to send a cookie yet.

<?php setcookie('heron','great blue'); ?>

Yes, sending that cookie was the right decision.

<?php ob_end_flush(); ?>

Discussion

You can pass ob_start( ) the name of a callback function to process the output buffer with that function. This is useful for postprocessing all the content in a page, such as hiding email addresses from address-harvesting robots:

<?php 
function mangle_email($s) {
    return preg_replace('/([^@\s]+)@([-a-z0-9]+\.)+[a-z]{2,}/is',
                        '<$1@...>',
                        $s);
}

ob_start('mangle_email'); 
?>

I would not like spam sent to ronald@example.com!

<?php ob_end_flush(); ?>

The mangle_email( ) function transforms the output to:

I would not like spam sent to <ronald@...>!

The output_buffering configuration directive turns output buffering on for all pages:

output_buffering = On

Similarly, output_handler sets an output buffer processing callback to be used on all pages:

output_handler=mangle_email

Setting an output_handler automatically sets output_buffering to on.

See Also

Recipe 10.11 uses output buffering in a database error logging function; documentation on ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.