PHP Output Buffering

By default, PHP sends the results of echo and similar commands to the browser after each command is executed. Alternately, you can use PHP’s output buffering functions to gather the information that would normally be sent to the browser into a buffer and send it later (or kill it entirely). This allows you to specify the content length of your output after it is generated, capture the output of a function, or discard the output of a built-in function

output buffering with the ob_start() function:


The optional callback parameter is the name of a function that post-processes the output. If specified, this function is passed the collected output when the buffer is flushed, and it should return a string of output to send to the browser

While output buffering is enabled, all output is stored in an internal buffer. To get the current length and contents of the buffer, use ob_get_length() and ob_get_contents()

$len = ob_get_length();
$contents = ob_get_contents();

If buffering isn’t enabled, these functions return false

There are two ways to throw away the data in the buffer. The ob_clean() function erases the output buffer but does not turn off buffering for subsequent output. The ob_end_clean() function erases the output buffer and ends output buffering

There are three ways to send the collected output to the browser (this action is known as flushing the buffer). The ob_flush() function sends the output data to the web server and clears the buffer, but doesn’t terminate output buffering. The flush() function not only flushes and clears the output buffer, but also tries to make the web server send the data to the browser immediately. The ob_end_flush() function sends the output data to the web server and ends output buffering. In all cases, if you specified a callback with ob_start(), that function is called to decide exactly what gets sent to the server

If your script ends with output buffering still enabled (that is, if you haven’t called ob_end_flush() or ob_end_clean()), PHP calls ob_end_flush() for you

Example of ob_start()


function callback($buffer)
  // replace all the apples with oranges
  return (str_replace("apples", "oranges", $buffer));


<p>It's like comparing apples to oranges.</p>



More Example of ob_start()

    ob_start();              // start output buffer 1
    echo "a";                // fill ob1
        ob_start();              // start output buffer 2
        echo "b";                // fill ob2
        $s1 = ob_get_contents(); // read ob2 ("b")
        ob_end_flush();          // flush ob2 to ob1
    echo "c";                // continue filling ob1
    $s2 = ob_get_contents(); // read ob1 ("a" . "b" . "c")
    ob_end_flush();          // flush ob1 to browser
    // echoes "b" followed by "abc", as supposed to:
    echo "<HR>$s1<HR>$s2<HR>";

Leave a Comment