In PHP, is there a way to capture the output of a PHP file into a variable without using output buffering?

Joe Lencioni picture Joe Lencioni · Oct 21, 2008 · Viewed 14.7k times · Source

In PHP, I want to read a file into a variable and process the PHP in the file at the same time without using output buffering. Is this possible?

Essentially I want to be able to accomplish this without using ob_start():

<?php
ob_start();
include 'myfile.php';
$xhtml = ob_get_clean();
?>

Is this possible in PHP?

Update: I want to do some more complex things within an output callback (where output buffering is not allowed).

Answer

Wes Mason picture Wes Mason · Oct 23, 2008

A little known feature of PHP is being able to treat an included/required file like a function call, with a return value.

For example:

// myinclude.php
$value = 'foo';
$otherValue = 'bar';
return $value . $otherValue;


// index.php
$output = include './myinclude.php';
echo $output;
// Will echo foobar