How do you define a PHP include as a string?

Viewed 19085

I tried:

$test = include 'test.php';

But that just included the file normally

6 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.

Try something like:

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

Try file_get_contents().

This function is similar to file(), except that file_get_contents() returns the file in a string.

Related