Handling Output

PHP is all about displaying output in the web browser. As such, there are a few different techniques that you can use to handle output more efficiently or conveniently.

Output Buffering

By default, PHP sends the results of echo and similar commands to the browser after each command is executed. Alternately, you can use PHP’s output buffering functions to gather the information that would normally be sent to the browser into a buffer and send it later (or kill it entirely). This allows you to specify the content length of your output after it is generated, capture the output of a function, or discard the output of a built-in function.

You turn on output buffering with the ob_start( ) function:

    ob_start([callback 
]);

The optional callback parameter is the name of a function that post-processes the output. If specified, this function is passed the collected output when the buffer is flushed, and it should return a string of output to send to the browser. You can use this, for instance, to turn all occurrences of http://www.yoursite.com/ to http://www.mysite.com/.

While output buffering is enabled, all output is stored in an internal buffer. To get the current length and contents of the buffer, use ob_get_length( ) and ob_get_contents( ):

    $len = ob_get_length( );
    $contents = ob_get_contents( );

If buffering isn’t enabled, these functions return false.

There are two ways to throw away the data in the buffer. The ob_clean( ) function erases the output buffer but does not turn ...

Get Programming PHP, 2nd Edition 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.