tags:

views:

261

answers:

5

I tried:

$test = include 'test.php';

But that just included the file normally

+5  A: 

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

//get anything that's in the output buffer, and empty the buffer
$oldOutput = 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.

timdev
Why is it necessary to stop any existing buffers? Output buffers in PHP stack: http://php.net/ob_start
jeremy
It isn't -- I just hadn't noticed the stackability. Editing my answer.
timdev
A: 

get_file_contents

antpaw
+1  A: 

Try something like:

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

you can use this function:

file_get_contents

http://www.php.net/manual/en/function.file-get-contents.php

assaqqaf
A: 

Have a look at the answers to this similar question.

mschuett