Reading buffers

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.

 

Next chapter: Other OB functions >>

Previous chapter: Flushing stacked buffers

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar