Caching PHP Operations

on Fri Aug 22 05:08:20 GMT 2008 in PHP and viewed 2980 times

How to use output buffers to cache code in PHP to make your applications run faster.


Everyone knows that PHP is a server side language, and takes time to parse. An example is my site before. It would load part of the content first, then it would do the rest. That was really annoying and could increase load time. Caching PHP is a simple way to make all the content display at one time, as it does now.

The basics of this is to use output buffering. To do this, the commands ob_start();, ob_get_contents();, and ob_end_clean(); are used.

To start off, one starts and ends the buffer like this:


  ob_start(); //starts the output buffer

  //commands go in here

  ob_end_clean(); // ends and cleans the buffer

That’s pretty much it. Next, we need to add something to the buffer. I’m just going to do something simple.


  ob_start();

  echo "Hi. This is in a buffer.";// displays some text

  $bufferContents = ob_get_contents(); // gets the contents of the buffer

  ob_end_clean();

Now what this does, is first I output text to the screen. But since this is in a buffer, it doesn’t actually display to the screen. Next I get the contents and put it into a variable. To use this all in all, I could do this:


  ob_start();

  echo "Hi. This is in a buffer.";// displays some text

  $bufferContents = ob_get_contents(); // gets the contents of the buffer

  ob_end_clean();

  echo "This text is outside the buffer.<br />";
  echo $bufferContents;

What this would display is:

This text is outside the buffer. Hi. This is in a buffer.

Easy. And it’s not limited to just echos in the buffer. You can do anything as long as it’s inside the buffer.