PHP Assign include content to a variable.

published on February 27th, 2008 · more from the blog →

So today i came across the need to include a file in php with limited access to data and not output it to the browser...

Basically all this does is buffer the output then get the buffer contents and return it...

// assigns the output of a file into a variable... lovely jubbly!
function get_include_contents($filename,$data='') {
    if (is_file($filename)) {
    	if (is_array($data)){
        include $filename;
        $contents = ob_get_contents();
        return $contents;
    return false;

I suppose a usage example might be nice
$data = array('name'=>'Ross','hobby'=>'Writing Random Code');
$output = get_include_contents('my_file.php',$data);
// my_file.php will now have access to the variables $name and $hobby

easy as pi :-p