Hudzilla.org - the homepage of Paul Hudson
Contents > Output Buffering Wish List | Report Bug | About Me ]

13.3     Getting started: ob_start(), ob_end_flush(), and ob_end_clean()

This is NOT the latest copy of this book; click here for the latest version.

bool ob_start ( [callback output_function])

bool ob_end_flush ( void )

bool ob_end_clean ( void )

There are two ways to start buffering output: through a setting in php.ini to enable output buffering for all scripts, or by using a function call on a script-by-script basis. Surprisingly, the latter is preferred - it makes your code more portable, and also gives you greater flexibility.

To create a new output buffer and start writing to it, call ob_start(). There are two ways to end a buffer, which are ob_end_flush() and ob_end_clean() - the former ends the buffer and sends all data to output, and the latter ends the buffer without sending it to output. Every piece of text outputted while an output buffer is open is placed into that buffer as opposed to being sent to output. Consider the following script:

<?php
    ob_start
();
    print
"Hello First!\n";
    
ob_end_flush();

    
ob_start();
    print
"Hello Second!\n";
    
ob_end_clean();

    
ob_start();
    print
"Hello Third!\n";
?>

That script will output "Hello First" because the first text is placed into a buffer then flushed with ob_end_flush(). The "Hello Second" will not be printed out, though, because it is placed into a buffer which is cleaned using ob_end_clean() and not sent to output. Finally, the script will print out "Hello Third" because PHP automatically flushes open output buffers when it reaches the end of a script.





<< 13.2 Performance Considerations   13.4 Reusing buffers: ob_flush() and ob_clean() >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
A PHP User - 16 Oct 2008

fhghj



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is seven plus zero?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow