Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page