Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you define a PHP include as a string?

Tags:

I tried:

$test = include 'test.php'; 

But that just included the file normally

like image 269
Ryan Avatar asked Jan 27 '10 20:01

Ryan


2 Answers

You'll want to look at the output buffering functions.

//get anything that's in the output buffer, and empty the buffer $oldContent = ob_get_clean();  //start buffering again ob_start();  //include file, capturing output into the output buffer include "test.php";  //get current output buffer (output from test.php) $myContent = ob_get_clean();  //start output buffering again. ob_start();  //put the old contents of the output buffer back echo $oldContent; 

EDIT:

As Jeremy points out, output buffers stack. So you could theoretically just do something like:

<?PHP function return_output($file){     ob_start();     include $file;     return ob_get_clean(); } $content = return_output('some/file.php'); 

This should be equivalent to my more verbose original solution.

But I haven't bothered to test this one.

like image 131
timdev Avatar answered Oct 21 '22 20:10

timdev


Try something like:

ob_start(); include('test.php'); $content = ob_get_clean(); 
like image 35
Brandon Avatar answered Oct 21 '22 18:10

Brandon