PHP
  Home arrow PHP arrow Page 5 - Output Buffering With PHP
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
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? 
PHP

Output Buffering With PHP
By: Harish Kamath, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 56
    2002-04-30

    Table of Contents:
  • Output Buffering With PHP
  • The Matrix Awaits
  • Start Me Up
  • Melting Down
  • Today's Forecast
  • Making It Simpler
  • The Real World
  • Zip Zap Zoom
  • Endgame

  • 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


    Output Buffering With PHP - Today's Forecast


    (Page 5 of 9 )

    As you saw on the previous page, you can display the contents of the current buffer at any time via a call to ob_end_flush(). If, however, you don't want to display the buffered output to the user, but instead want to do something else with it - write it to a file, for example - you have a couple of options.

    The first - and simplest - involves using ob_get_contents() to extract the current contents of the output buffer to a PHP variable, and then processing that variable to get the results you desire. Here's a quick example:

    <?php// start buffering the outputob_start();// output format - either "www" or "file"$output = "file";// send some output?><html><head><basefont face="Arial"></head><body><?// open connection to database$connection = mysql_connect("localhost", "joe", "nfg84m") or die("Unable to connect!");mysql_select_db("weather") or die ("Unable to select database!");// get data$query = "SELECT * FROM weather";$result = mysql_query($query) or die ("Error in query: $query. " .mysql_error());// if a result is returnedif (mysql_num_rows($result) > 0){ // iterate through resultset // print data while (list($temp, $forecast) = mysql_fetch_row($result)) { echo "Outside temperature is $temp"; echo "<br>"; echo "Forecast is $forecast"; echo "<p>"; }}else{ echo "No data available";}// close database connectionmysql_close($connection);// send some more output?></body></html><?php// now decide what to do with the buffered outputif ($output == "www"){ // either print the contents of the buffer... ob_end_flush();}else{ // ... or write it to a file $data = ob_get_contents(); $fp = fopen ("weather.html", "w"); fwrite($fp, $data); fclose($fp); ob_end_clean();}?>
    In this case, the ob_get_contents() function is used to retrieve the current contents of the output buffer, and write it to a file.

    Alternatively, you might want to use a callback function that is invoked every time output is caught by the buffer. The name of this user-defined callback function must be specified as an argument during the initial call to ob_start(), and the function itself must be constructed to accept the contents of the buffer as function argument.

    If that sounded way too complicated, the next example, which rewrites the one above to use this technique, should make it clearer.

    <?php// user-defined output handlerfunction myOutputHandler($buf){ global $output; // either dump the buffer to a file if ($output != "www") { $fp = fopen ("weather.html", "w"); fwrite($fp, $buf); fclose($fp); } // ... or return it for printing to the browser else { return $buf; }}// start buffering the output// specify the callback functionob_start("myOutputHandler");// output format - either "www" or "file"$output = "www";// send some output?><html><head><basefont face="Arial"></head><body><?// open connection to database$connection = mysql_connect("localhost", "joe", "nfg84m") or die("Unable to connect!");mysql_select_db("weather") or die ("Unable to select database!");// get data$query = "SELECT * FROM weather";$result = mysql_query($query) or die ("Error in query: $query. " .mysql_error());// if a result is returnedif (mysql_num_rows($result) > 0){ // iterate through resultset // print data while (list($temp, $forecast) = mysql_fetch_row($result)) { echo "Outside temperature is $temp"; echo "<br>"; echo "Forecast is $forecast"; echo "<p>"; }}else{ echo "No data available";}// close database connectionmysql_close($connection);// send some more output?></body></html><?php// end buffering// this will invoke the user-defined callbackob_end_flush();?>
    In this case, when ob_end_flush() is called, PHP will invoke the user-defined function myOutputHandler(), and will pass the entire contents of the buffer to it as a string. It is now up tp the function to decide what to do with the buffer - in this case, I've used the $output variable to decide whether or not to write it to a file. You can just as easily write a function to process it in some other way - for example, run a search-and-replace operation on the buffer, write it to a database, or email it to a specific address.

    More PHP Articles
    More By Harish Kamath, (c) Melonfire


     

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT