Search code examples
phpevaloutput-buffering

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


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


Solution

  • 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