Home arrow PHP arrow Page 5 - Output Buffering With PHP

Today's Forecast - PHP

Hate those ugly error messages that PHP generates when it encounters an error in your scripts? Can't stand half-constructed Web pages? Well, maybe you should take a look at PHP's output control functions, which offer an interesting and powerful solution to the problem.

TABLE OF CONTENTS:
  1. Output Buffering With PHP
  2. The Matrix Awaits
  3. Start Me Up
  4. Melting Down
  5. Today's Forecast
  6. Making It Simpler
  7. The Real World
  8. Zip Zap Zoom
  9. Endgame
By: Harish Kamath, (c) Melonfire
Rating: starstarstarstarstar / 69
April 30, 2002

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: