Template engines such as Smarty often talk about template caching. Usually, these engines offer an in-built mechanism for storing a compiled version of a template (i.e. the native PHP generated from the template), which prevents us having to recompile the template every time a page is requested. This should not be confused with output caching, which refers to the caching of the rendered HTML (or other output) that PHP sends to the browser. You can successfully use both types of caching together on the same site.
Here, we’ll look at PHP’s in-built caching mechanism, the output buffer, which can be used with whatever page rendering system you prefer (templates or no templates). Consider a situation in which your script displays results using, for example, echo or print, rather than sending the data directly to the browser. In these cases, you can use PHP’s output control functions to store the data in an in-memory buffer, which your PHP script has both access to and control over.
// Start buffering the output
// Echo some text (which is stored in the buffer);
echo '1. Place this in the buffer<br />';
// Get the contents of
$buffer = ob_get_contents();
// Stop buffering and clean out the buffer
// Echo some text normally
echo '2. A normal echo<br />';
// Echo the contents from the buffer
The buffer itself stores the output as a string. So, in the above script, we commence buffering with ob_start and use echo to display something. We then use ob_get_contents to fetch the data the echo statement placed in the buffer, and store it in a string. The ob_end_clean function stops the output buffer and trashesm the contents; the alternative is ob_end_flush, which displays the contents of the