Output BufferingSince version 4, PHP has supported output buffering. Output buffering allows you to have all output from a script stored in a buffer instead of having it immediately transmitted to the client. Chapter 9 looks at ways that output buffering can be used to improve network performance (such as by breaking data transmission into fewer packets and implementing content compression). This chapter describes how to use similar techniques to capture content for server-side caching. If you wanted to capture the output of a script before output buffering, you would have to write this to a string and then echo that when the string is complete: <?php $output = "<HTML><BODY>"; $output .= "Today is ".strftime("%A, %B %e %Y"); $output .= "</BODY></HTML>"; echo $output; cache($output); ?> If you are old enough to have learned Web programming with Perl-based CGI scripts, this likely sends a shiver of painful remembrance down your spine! If you're not that old, you can just imagine an era when Web scripts looked like this. With output buffering, the script looks normal again. All you do is add this before you start actually generating the page: <?php ob_start(); ?> This turns on output buffering support. All output henceforth is stored in an internal buffer. Then you add the page code exactly as you would in a regular script: <HTML> <BODY> Today is <?= strftime("%A, %B %e %Y") ?> </BODY> </HTML> After all the content is generated, you grab the content and flush it: <?php $output = ob_get_contents(); ob_end_flush(); cache($output); ?> ob_get_contents() returns the current contents of the output buffer as a string. You can then do whatever you want with it. ob_end_flush() stops buffering and sends the current contents of the buffer to the client. If you wanted to just grab the contents into a string and not send them to the browser, you could call ob_end_clean() to end buffering and destroy the contents of the buffer. It is important to note that both ob_end_flush() and ob_end_clean() destroy the buffer when they are done. In order to capture the buffer's contents for later use, you need to make sure to call ob_get_contents() before you end buffering. |