Recipe 8.12. Buffering Output to the Browser


8.12.1. Problem

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

8.12.2. 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. This is demonstrated in Example 8-31.

Buffering output

<?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(); ?>

8.12.3. 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. Such a callback is shown in Example 8-32.

Using a callback with ob_start( )

<?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.

8.12.4. See Also

Documentation on ob_start( ) at http://www.php.net/ob-start, ob_end_flush( ) at http://www.php.net/ob-end-flush, and output buffering at http://www.php.net/outcontrol.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net