PHP Output Buffering (Very Simple Examples)

Welcome to a tutorial and examples on how to use PHP output buffering. You have probably seen this output buffering thing everywhere on the Internet, maybe even used it yourself. But just what is output buffering, and what does it do!?

With output buffering, PHP will hold data in the buffer and only release them at the end of the script (or when “buffer flush” is called). For example:

  • ob_start();
  • echo "hello";
  • echo " cyber ";
  • echo "world";
  • ob_flush();

Instead of doing 3 separate echo, this will hold “hello cyber world” in the buffer and collectively release them as a single output.

That’s all for the basics, but let us walk through more examples in this guide – Read on!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

PHP OUTPUT BUFFERING EXAMPLES

All right, let us now get into the examples of using output buffering in PHP.

 

EXAMPLE 1) OB START & FLUSH

1-ob-start-flush.php
<?php
// (A) START BUFFERING
ob_start();

// (B) HOLD "HELLO" AND " WORLD" IN THE BUFFER
echo "hello";
echo " world";

// (C) RELEASE "HELLO WORLD" AS SINGLE OUTPUT
// NOTE: PHP WILL AUTO-FLUSH AT END-OF-SCRIPT EVEN IF OB_FLUSH() IS OMITTED
ob_flush();

As with the introduction above:

  1. Calling ob_start() will start the output buffering.
  2. echo "hello" and echo " world" will not immediately output, but be stored in the buffer.
  3. Calling ob_flush() will release "hello world" inside the buffer as a single string.

Take note that even if ob_flush() is omitted – PHP will still automatically release the buffer at the end of the script.

 

EXAMPLE 2) OB CLEAN

2-clean.php
<?php
// (A) START BUFFERING
ob_start();

// (B) HOLD "HELLO" AND " WORLD" IN THE BUFFER
echo "hello";
echo " world";

// (C) CLEAN THE BUFFER
ob_clean();
 
// (D) NOTHING WILL OUTPUT SINCE THE BUFFER IS EMPTY NOW
ob_flush();

To “cancel”, we can use ob_clean() will clear everything out of the output buffer. How this example goes –

  • (A & B) "hello" and " world" are first collected into the buffer.
  • (C) ob_clean() empties the buffer.
  • (D) Since the buffer is now empty, PHP has nothing to output at the end of the script.

 

 

EXAMPLE 3) OB DOES NOT STOP AUTOMATICALLY

3-ob-no-stop.php
<?php
// (A) START BUFFERING
ob_start();

// (B) BUFFER NOW HOLDS "HELLO WORLD"
echo "hello";
echo " world";

// (C) CLEAN - BUFFER NOW EMPTY
ob_clean();

// (D) OUTPUT BUFFERING IS STILL ON!
// BUFFER NOW HOLDS "FOO BAR"
echo "foo";
echo " bar";
ob_flush();

Before we move into the next example, this is something to take extra note of. Calling ob_clean() and ob_flush() will not stop buffering. Whatever output after calling these functions will still be cached inside the buffer.

 

EXAMPLE 4) OB END

4-ob-end.php
<?php
// (A) HOLD "HELLO WORLD" IN BUFFER
ob_start();
echo "hello ";
echo "world";

// (B) STOP BUFFERING
// (B1) END CLEAN
// EMPTY BUFFER + STOP STOP BUFFERING (NOTHING WILL OUTPUT)
// ob_end_clean(); 

// (B2) END FLUSH
// OUTPUT "HELLO WORLD" + STOP BUFFERING
ob_end_flush();

// (C) BACK TO "NORMAL OUTPUT"
echo "foo bar"; // IMMEDIATELY OUTPUT "FOO BAR"

As you already know, ob_clean() and ob_flush() will not stop the buffering. To stop buffering, we need to explicitly instruct PHP to do so:

  • ob_end_clean() Clear all the contents inside the buffer, then stop buffering.
  • ob_end_flush() Output all the contents inside the buffer, then stop buffering.

 

 

EXAMPLE 5) GET BUFFER

5-ob-get.php
<?php
// (A) HOLD "HELLO WORLD" IN BUFFER
ob_start();
echo "hello world";

// (B) GET BUFFER LENGTH (IN BYTES)
echo " - ".ob_get_length()." bytes";

// (C) GET OUTPUT BUFFER
// (C1) GET - SIMPLY "COPY" BUFFER INTO VARIABLE
$buff = ob_get_contents();

// (C2) GET CLEAN  - "MOVE" BUFFER INTO VARIABLE, EMPTY BUFFER
// $buff = ob_get_clean();

// (C3) GET FLUSH - OUTPUT BUFFER + COPY TO VARIABLE
// $buff = ob_get_flush();

// (D) WHAT'S IN $BUFF?
ob_end_clean();
echo $buff;

So what’s in the buffer? There are 4 functions that we can use to fetch contents from the buffer:

  • ob_get_length() gets the size of the buffer, in bytes.
  • ob_get_contents() fetches whatever is inside the buffer.
  • ob_get_clean() return the buffer and empty it.
  • ob_get_flush() return the buffer and immediately output it.

 

 

EXAMPLE 6) A USEFUL EXAMPLE

With that, some of you guys should be thinking – What practical use does output buffering have? So here is an actually useful example.

 

6A) DUMMY PRODUCTS

6a-products.php
<?php
$products = [
  [
    "name" => "Foo Bar",
    "price" => "12.34"
  ],
  [
    "name" => "Poo Bar",
    "price" => "22.33"
  ],
    [
    "name" => "Goo Bar",
    "price" => "33.44"
  ]
];

Let us just pretend that we have a long list of products in the database that need to be displayed on an HTML page.

 

6B) OUTPUT BUFFERING TO STATIC FILE

6b-html.php
<?php
// (A) USE STATIC HTML PAGE IF EXISTS
if (file_exists("products.html")) { require "products.html"; }
 
// (B) GENERATE + SAVE PAGE IF NOT
else {
  // (B1) GET PRODUCTS
  require "6a-products.php";
 
  // (B2) START BUFFERING
  ob_start();
 
  // (B3) OUTPUT PRODUCTS HTML
  foreach ($products as $p) {
    echo "<div>".$p["name"]."</div>";
    echo "<div>".$p["price"]."</div>";
  }
 
  // (B4) SAVE AS STATIC HTML
  file_put_contents("products.html", ob_get_contents());
  ob_end_flush();
}

So the common way of doing it is – Every time a user accesses the products page, we connect to the database, fetch the products, then generate the list of products in HTML.

This is where output buffering comes in handy. Why don’t we capture the HTML in the buffer, then save it into a static HTML page? So in the future, things will load a lot faster by serving a static HTML file instead of reading from the database and regenerating the entire page.

 

 

EXTRAS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

THE SUMMARY

Function Description
ob_start() Start buffering.
ob_clean() Clean out the buffer, no output.
ob_flush() Output and clean out the buffer.
ob_end_clean() Clean out the buffer, and stop buffering.
ob_end_flush() Output the buffer, clean it, and stop.
ob_get_contents() Returns the current buffer contents.
ob_get_clean() Returns the current buffer contents, then cleans it out.
ob_get_flush() Returns the current buffer contents, output it immediately, then clean it out.
ob_get_length() Get the size of the buffer, in bytes.

But of course, these are only a few of the common basics of output buffering. If you need more output buffering yoga – Please visit the official PHP function reference.

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

1 thought on “PHP Output Buffering (Very Simple Examples)”

Leave a Comment

Your email address will not be published. Required fields are marked *