13.7 Reading buffers: ob_get_contents()This is NOT the latest copy of this book; click here for the latest version.
string ob_get_contents ( void )
Output buffers are two-way affairs, which means you can read from them as well as write to them. You've seen that writing to an output buffer is simply a matter of opening a buffer and outputting text as normal - reading that data back is done by just using the ob_get_contents() function.
Ob_get_contents() takes no parameters, and returns the full contents of the most recent buffer. Let's take a look at how that might be used:
<?php
$result = mysql_query("SELECT * FROM EmployeeTable WHERE ID = 55;");
while ($row = mysql_fetch_assoc($result)) {
extract($row);
print "Some info A: $SomeInfoA\n";
print "Some info B: $SomeInfoB\n";
print "Some info C: $SomeInfoC\n";
...[snip]...
print "Some info Z: $SomeInfoZ\n";
} ?>
Above we have a basic script to grab an employee from a database and output their information to the screen. As you can see, it is probably quite long, so what do we do if we wanted the same information to be stored in a file as opposed to being shown on screen? Write the script again? With output buffering we can change the script to this next example and save ourselves the hassle:
<?php
ob_start()
$result = mysql_query("SELECT * FROM EmployeeTable WHERE ID = 55;");
while ($row = mysql_fetch_assoc($result)) {
extract($row);
print "Some info A: $SomeInfoA\n";
print "Some info B: $SomeInfoB\n";
print "Some info C: $SomeInfoC\n";
...[snip]...
print "Some info Z: $SomeInfoZ\n";
}
$output = ob_get_contents();
ob_end_clean();
file_put_contents("employee.txt", $output); ?>
Once output is no longer sent out of our reach, a whole new horizon of possibilities come into view - above we treat output like a scratch pad, which is what output buffering is all about, really.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|