PHP Assign include content to a variable.

February 27th, 2008
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)){
		extract($data);
    	}
        ob_start();
        include $filename;
        $contents = ob_get_contents();
        ob_end_clean();
        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

Comments

mark

February 27th, 2008 6:00pm
huh?
lol

Scrivna

March 3rd, 2008 8:19pm
It's useful for loading content from a template or sumthing then storing it for output at a later time. :-)

Jason

March 17th, 2008 9:42pm
Wow, Scrivna you are the bomb! This little bit of code helped me out of a bind in a jiffy, thank you very much!

Cal

April 5th, 2008 4:46pm
Hello,
Google search brought me here. How do I assign the entire
include to a variable for later use?

Help me resolve this?
[code]
assign var=$content value=include_once($sourcedir . '.$pgcontent.');
// ABOUT 300 LINES DOWN THE PAGE

$content

[/code]

Thanks,
Cal

Cal

April 7th, 2008 7:56pm
get_include_contents is not going to work if the include is a php script.
It will just return the unparsed text. How do I assign variable $content to

include_once($sourcedir . ‘.content.php.’);

or maybe just to print, echo, or return the results of the script using
$content?

Thanks in advance,
cal

Cal

April 8th, 2008 2:23pm
For the record, I was able to resolve my own
problem, call the include using the variable
$content, like this:

ob_start();
include 'file.php';
$content = ob_get_clean();

echo $content; // display the parsed output of file.php, "echo" not necessary

Cal
.