ncyoung.com

php out buffers to better use php templating in functions

This entry is in the following categories:

Top->Programming->Web->PHP
 - Jump to newest entry: php documentation generator
 - Newer in PHP: auto convert < br > tags in php

I figured out a cool trick for PHP. I've always noticed that the templating engines fall down when you begin to write subroutines. In other words, if you want to return string output from a function rather than immediately printing that as the function runs, you must use string concatenation rather than PHP's templates.



For example:


$string = tester();
print "this will print second<br>";
print $string; //will do nothing

function tester(){
?>
this will print first.
<?php
}

But you can use PHP's nifty output buffering to save up all the template output within the subroutine like so:



$string = tester();
print "this will now be first<br>";
print $string;

function tester(){
ob_start();
?>
this will be second.
<?php
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}

Nifty, huh?



Dated: 09/04/2002