Monday, November 05, 2012

Output buffering in PHP


I have a very small yet so interesting code sample on buffering in PHP.

Suppose, I have my web-page divided in two segments.. 

1. Main PHP [main.php] for all logic.
2. Template PHP file [template.php], which I include at the bottom of main.php.

Main.php
----------
<?php
include("template.php");
?>

template.php
----------------
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
This is a test template. This test template works well. I want to learn more about PHP templates. This test template is finally working perfectly.
</body>
</html>


Problem :: How to change all occurrences of the word "test template" to "template" without modifying the template file itself?

Solution :: We can manipulate the buffer features that comes with PHP and by doing that we can make required changes to the output PHP script generates before rendering onto browser. 

We need to change the main.php as shown below.

<?php
function show($buffer)
{
  return str_replace("test template","template",$buffer);
}

// Start The Buffer with show() function 
// as a callback ob_start("show"); 
include("template.php");

// Send the Buffer content to Browser
ob_end_flush();
?>

The line "ob_start('show')" line tells PHP server to start buffering the server output and apply the show() function as CallBack on the output. That means, all occurrences of the phrase "test template" are changed to "template" before they are finally sent to browser. And lastly, ob_end_flush() function renders the output to the browser. So, the output of the above script is shown below.

This is a template. This template works well. I want to learn more about PHP templates. This template is finally working perfectly.

No comments: