Sunday, February 15, 2009

PHP Output Buffering

wow, it's been awhile already but i'm back to post more PHP-related articles. lately i'm busy working on another project for Microsoft Imagine Cup - the round 1 ends on 27 Feb 09.

Normally when most PHP programmers codes their PHP application, they'll have something like this - PHP in HTML:
<ul>
<li><b><?php echo $tabs[0]; ?></b></li>
<li><b><?php echo $tabs[1]; ?></b></li>
<li><b><?php echo $tabs[2]; ?></b></li>
</ul>


Why not have your HTML codes buffered in your own PHP variable and process it before echo to output like this?
<?php
$buffer .= '<ul>';
$buffer .= '<li><b>'.$tabs[0].'</b></li>';
$buffer .= '<li><b>'.$tabs[1].'</b></li>';
$buffer .= '<li><b>'.$tabs[2].'</b></li>';
$buffer .= '</ul>';';

echo $buffer;
?>


Also when you buffer using the 2nd method, you can reduce the need of removing whitespaces and newline characters in the HTML output, thus increasing the efficiency of your application.

With the $buffer variable, you can also post-process the buffer by applying custom tags. an example:
<?php
$buffer .= '<ul>';
$buffer .= '<li><b><$tab1$></b></li>';
$buffer .= '<li><b><$tab2$></b></li>';
$buffer .= '<li><b><$tab3$></b></li>';
$buffer .= '</ul>';';

echo str_ireplace(array('<$tab1$>','<$tab2$>','<$tab3$>'),array($tab[0],$tab[1],$tab[2]),$buffer);
?>


Isn't that great? Hope this helps for you. I am Sam Yong, your multi-disciplinary software developer major in PHP, signing off.

No comments: