Miscellaneous
  Home arrow Miscellaneous arrow Page 4 - PHP Output Buffering
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Download TestComplete 
Forums Sitemap 
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MISCELLANEOUS

PHP Output Buffering
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 15
    2003-06-10

    Table of Contents:
  • PHP Output Buffering
  • How It's Done
  • Callback Functions
  • Examples
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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($fhob_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 "&lt;p align=center&gt;&lt;small&gt;Copyright &amp;copy; "
                   
    implode(","range(2002date('Y')))
                   . 
    "&lt;/small&gt;&lt;/p&gt;";
        
        
    // 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.

    More Miscellaneous Articles
    More By Codewalkers


       · This is the tutorial that taught me output buffering. Thank you, Mike, for an...
       · Very Very Good and complete tutorial.Thank You.regardsSatya Prakash
     

    MISCELLANEOUS ARTICLES

    - Install Slackware on Your Old PC
    - Firefox Plugins You`re Not Using (and Should...
    - Working with MP3 ID3 Tags in FTP Server Usin...
    - How Switching to Linux Can Make Your Computi...
    - Set Up Your Home Office on Linux: a Guide fo...
    - Putty File Transfer Commands in SSH Protocol
    - Setting Up Ubuntu for Your Home Office
    - Installing Mint Linux
    - Crucial Traits of Awk
    - Using PHP to Stream MP3 Files and Prevent Il...
    - 10 Must Have Firefox Improvements
    - All About OpenOffice 3.0
    - Shell Script Writing
    - Loops in the UNIX Shell
    - The Test in the UNIX Shell





    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek