Including a php file into a string

… Because there will be times in which you may want to include the contents of a php file into a variable.

	function get_include_contents($filename) {

	    if (is_file($filename)) {
	        ob_start();
	        include $filename;
	        $contents = ob_get_contents();
	        ob_end_clean();
	        return $contents;
	    }
	    return false;
	}

I have edited my post to answer dave’s comment below.

By looking at this funciton you may think it’s just a substitute of file_get_contents().
The difference is that file_get_contents will return literaly the contents of the file, as opposed to get_include_contents that will actually run the code,
and because we are turning on output buffering, we can get the output of the script and store it in a string. For example if we have the php file ‘example.php’:


	echo 'The gamma laser toxic spill gave me powers';

file_get_contents will produce the following result:


	$string = file_get_contents('example.php');

	echo $string;
	// will output: echo 'The gamma laser toxic spill gave me powers';

If we use get_include_contents() instead, it will produce the following result:


	$string = get_include_contents('example.php');

	echo $string;
	// will output: The gamma laser toxic spill gave me powers

If you are still thinking why would I want to do this, I will give you a real life example to ilustrate:

Lets assume that you have the following email template in a file template.php:


echo  'Dear Mr. ' . $params['name'] . ',';
echo  'All your ' . $params['item'] . ' are belong to us!';

The function could then be extended to accept some paramaters that the template will need to have on scope:

	function get_include_contents($filename, $params) {

	    if (is_file($filename)) {
	        ob_start();
	        include $filename;
	        $contents = ob_get_contents();
	        ob_end_clean();
	        return $contents;
	    }
	    return false;
	}

After that we can send an email using template.php like this:


	$html_email = get_include_contents(
							   'example.php'
							   array(
								   'name'  =>; 'Satan',
							           'item'  => 'Snakes'
								  )
							);

	mail('someemail@blah.com', 'Subject', $html_email);	

The recipient of the email will have a message in his inbox saying:


Dear Mr. Satan,
All your snakes are belong to us!