Skip Navigation

Cheap Output Buffering

Be The First To Comment! »»

A common way for developers to make standard layouts in PHP is to create header and footer include files and then call them from each page. Like so:

<? include('header.php'); ?>
<h2>Web Page&lt/h2>
... etc ...
<? include('footer.php'); ?>

Something I learned using Fusebox is to create layout files that are called last, store the content into a variable and echo the content in the layout file. This method is preferable to me instead of using headers and footers, since it lets you edit your layout files as a whole.

Also, in the case of globally included headers and footers, you didn't end up with the header output being sent on URLs where you didn't need it. If you needed a form action page that only did processing and then redirected then you simply did your processing without calling the layout at the end. The header file output wasn't already sent, and you didn't worry about the footer. This saves testing for "http headers sent" and using JavaScript redirection, which can be unreliable depending on the browser.

The trick with the layout file method is to somehow set your content to a variable. The best way is to use output buffering. But what if you're not comfortable using output buffering? What if your server doesn't support it or in some way you're not able to use it?

Here's a simple solution: make your content into a function and call that function from the layout page like so:

a page on your site:

<?
function pageContent () {
?>
<h2>Web Page&lt/h2>
... etc ...
<?
}

<? include('layout.php'); ?>

The layout.php file:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>My Web Site</title>
</head>
<body>
... layout elements ...
<?
pageContent();
?>
... layout elements ...
</body>
</html>

It's not the most complex idea but it might get your creative thoughts flowing. One question might be: how can I "append" to the content?

Sep 17, 2005 |

«« Previous Entry  ·  Next Entry »»

Comments


How to Put Your Face Next to Your Comment

Add Your Comment to:  Cheap Output Buffering


(Required not Shown)

(Optional, use http://yoursite.com and I'll Link with 'Follow')



"The secret to creativity is knowing how to hide your sources." -- Einstein