Reading Buffers
Output buffers are two-way affairs, which means you can read from them as well as write to them. So far we have only covered writing data; reading that data back is done by using the ob_get_contents()
function.
The ob_get_contents()
function takes no parameters and returns the full contents of the most recently opened buffer. For example:
$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"; }
That script sends its data (presumably lots of employee data) to the screen. With output buffering, we can change it to save to a file, like this:
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);
That scripts treats output like a scratch pad, saving it to a file rather than sending it to output.
Get PHP in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.