PHP Output Buffering - Examples
(Page 4 of 5 )
Now that we are all experts with output buffering, let's examine a few examples of what output buffering can do for us. We will first examine a simple method of caching pages that require a large amount of processor time to execute, so you only have to update the information when absolutely necessary. We will then see how to catch the output from functions like fileread(). The last example is how to add footer functions.
Caching with PHP Recently I wrote a script which took a long time to run. There was a very large list of race results for a 5K. The script loaded the results from a CSV spreadsheet file and output them in a visually pleasing format. With the size of the spreadsheet, the parsing took an extremely long time. This definitely wouldn't do, but then my good friend output buffering came and joined my side.
The following code shows how output buffering can be employed to cache whole pages or sections of pages. A call is made to parse_spreadsheet() which is not a real function. This simply exists to represent a function which parses the spreadsheet. In testing this snippet, replace this line with a function you have prepared. The name of the cache file and spreadsheet are stored in the constants CACHE_FILE and SPREADSHEET_FILE respectively.
<?php // Define file locations define(CACHE_FILE, "./spreadsheet_cache"); define(SPREADSHEET_FILE, "./spreadsheet.csv");
// Check which has been updated most recently, the spreadsheet or cache if (@filemtime(SPREADSHEET_FILE) > @filemtime(CACHE_FILE)) { // Initiate output buffering ob_start(); // Parse the spreadsheet parse_spreadsheet();
// Write the buffer to the cache file $fh = fopen(CACHE_FILE, "w"); fwrite($fh, ob_get_contents()); fclose($fh);
// End the output buffer and display the contents ob_end_flush();
// If the cache is newer than the spreadsheet, simply display // the cache file rather than parsing again } else { readfile(CACHE_FILE); } ?> |
One should not think that this technique is limited to spreadsheets only. Another useful example is when data must be retrieved from a database. This works well in any situation where a lot of data needs to be parsed on a regular basis which is possibly very time consuming. Simply replace parse_spreadsheet() with the appropriate display function and the if statement with an appropriate method of detecting whether the data should be updated or if the cache can be used.
Catching Text from Functions There aren't too many things that annoy me. My entire list could be enumerated as follows: cats, people who buy 300 individual cans of soup yet count it as one item in the express lane, and functions like fileread(). I can't offer any solutions for the first two (no legal solutions at least), but the third I can.
By functions like fileread() I am implying functions which simply dump their output to the output buffer rather than returning their output as a string. A brief list (by no means comprehensive) of such functions is: passthru(), fpassthru(), system(), etc. These functions are extremely annoying when you are simply trying to obtain and parse the output. Thankfully, our good friend output buffering comes to the rescue.
The following snippet shows how to read an entire file into a variable very easily.
<?php // Start output buffering ob_start(); // Load file contents readfile("data.txt"); // Transfer the contents into a variable $data = ob_get_contents(); // Close the output buffering ob_end_clean(); ?> |
The entire contents of data.txt are now stored in $data. It is obvious how one could easily replace readfile() with any of the previously mentioned functions to capture any sort of function output into a variable. For example, to run a shell script and suppress the results can be accomplished in the same way but without placing the output buffer contents in a variable.
Footers In most PHP applications header files are included at the beginning of each script to handle such things as initiating database connections, loading libraries, instantiating classes, etc. There are often things which should be done at the end of each script as well, such as parsing templates, closing connections, etc. In the past, I have been forced to explicitly call these functions in each seperate script. I didn't know of anyway to globally set such footer functions, until now.
Output buffering with the use of a callback function allows the use of footer functions without having to edit the php.ini file. We will first examine a very simple example. Including the following snippet at the top of a script will cause a copyright message to be appended to the bottom of the page.
<?php // Start output buffering with a callback function ob_start("footer_copyright");
// Function called when the output buffer is flushed function footer_copyright($buffer) {
// Generate the copyright message $copyright = "<p align=center><small>Copyright &copy; " . implode(",", range(2002, date('Y'))) . "</small></p>"; // Return the composite buffer return $buffer.$copyright; } ?> |
The footer function need not only deal with adding text to the page. You can perform any operation within this footer function as you would anywhere else. Therefore, you could increment counters, close file handles, finalize object instances, etc. The only thing you cannot do inside a output buffering handler is output buffering. This should not be too large of a restriction though.
Next: Conclusion >>
More Miscellaneous Articles
More By Codewalkers