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 = mysqli_query($db, "SELECT * FROM EmployeeTable WHERE ID = 55;");

    while ($row = mysqli_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 = mysqli_query($db, "SELECT * FROM EmployeeTable WHERE ID = 55;");

    while ($row = mysqli_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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Other OB functions >>

Previous chapter: Flushing stacked buffers

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.