Saturday, December 10, 2011

Saving includes to a variable

I was reading a forum post and they wanted to save an include to a variable when making new forums on their website. I thought about it and here is what I came up with:
<?php
function get_include($path, $cat_id = null){
     ob_start(); // start buffer
     include $path;
     $content = ob_get_contents(); // assign buffer contents to variable
     ob_end_clean(); // end buffer and remove buffer contents
     return $content;
}
$render = array();
$render[] = "testing1";
$render[] = "testing2";
$category['fid'] = '134';
echo "<pre>";
$render[] = get_include('add_forum.php', $category['fid']);
$render[] = get_include('add_forum.php', $category['fid']);
print_r($render);
?>



and the forum_add.php looks like this:
<?php
echo "here is your id: $cat_id";
?>


The result looks like:
Array
(
    [0] => testing1
    [1] => testing2
    [2] => here is your id: 134
    [3] => here is your id: 134
)



Isn't this a nice way of both saving an include to a file and passing a variable to the include in a function.