Академический Документы
Профессиональный Документы
Культура Документы
by Michael Bailey
2003-06-10
Synopsis
This tutorial will procede first by enumerating the functions used in output buffering with
a brief explanation of each. Then we will examine how these functions are utililized. We
will conclude with three brief examples of scenerios where one might use output
buffering.
http://codewalkers.com/tutorials/44/1.html
Page 1
Introduction
Today I want to answer a question which has vexed mankind for centuries, "How do I
get my suit dry-cleaned without that disgusting chemical smell? And can I get it done
overnight?" Unfortunately, I don't have the slightest idea how to answer that question,
so I'm forced instead to discuss output buffering in PHP. That's how life is some times.
Output buffering is a powerful tool in PHP which allows you to buffer a script's output.
You can then edit this buffer before returning it to the client.
This tutorial will procede first by enumerating the functions used in output buffering with
a brief explanation of each. Then we will examine how these functions are utililized. We
will conclude with three brief examples of scenerios where one might use output
buffering. Without further ado then, we will procede to...
http://codewalkers.com/tutorials/44/1.html
Page 2
$buffer = ob_get_contents();
// Stop buffering
ob_end_clean();
// Display the buffer
print "'$buffer'";
?>
The output isn't all that exciting, simply Hello World in single quotes. The function
ob_start() initiates the output buffering. "Hello World" is then printed, but it does not get
sent to the client. Instead it is buffered until we do something with it. That we do by
storing the buffer in $buffer by calling ob_get_contents(). ob_end_clean() ends the
output buffering, which means that the last print command displays to the client.
Without knowledge of output buffering, one would expect the lines to be printed in
http://codewalkers.com/tutorials/44/1.html
Page 3
numerical order. This is not the case though. After printing line 1, a second buffer is
opened which prints line 2 and captures the buffer. Line 3 is then printed in the first
buffer. The first buffer captures lines 1 and 3 while the second captures line 2.
What all this means is that you can build functions and scripts with output buffering
without worrying about fouling up an algorithm nested below or above in the logic. As
long as you always remember to close every buffer you open, you won't have any
problems.
Callback Functions
Arguably the most powerful element of output buffering is the capability of defining
callback functions. You can define a function to be called when the buffer is flushed to
the screen. This callback function receives the buffer as a parameter. The returned
value is then printed.
<?php
// Start buffering with a callback function
ob_start("callback");
print "Line 1\n";
print "Line 2\n";
// Flush the contents
ob_flush();
print "Line 3\n";
// Define the callback function
function callback($buffer) {
return "Here's the buffer: $buffer";
}
?>
The script displays lines 1 through 3. After printing line 2, the buffer is flushed. This
passes the data to the callback function, which prepends to trite little message. Since
the buffer isn't closed before the end of the script, PHP automatically flushes the buffer,
which calls the callback function once again. One of the examples below deals with
callback functions more in depth.
There are a couple of things to remember when using callback functions. You have to
return what you want to displayed, not print it. The print command doesn't work in the
callback function. Also, you cannot use output buffering inside of a callback function.
It's because of some United Nations resolution or something. It just can't be done, so
don't try it.
Examples
Now that we are all experts with output buffering, let's examine a few examples of what
http://codewalkers.com/tutorials/44/1.html
Page 4
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.
http://codewalkers.com/tutorials/44/1.html
Page 5
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.
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.
http://codewalkers.com/tutorials/44/1.html
Page 6
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.
Conclusion
Output buffering is one of those parts of PHP which often gets overlooked. This is
unfortunate since wise use of output buffering can simplify many projects. Once you
learn to use it proficiently, you will find numerous scenarios where it can be used that
you'd never thought of before.
http://codewalkers.com/tutorials/44/1.html
Page 7