Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 237
Joe Lencioni Avatar asked Oct 21 '08 18:10

Joe Lencioni


People also ask

How do I display the output of a PHP file?

With PHP, there are two basic ways to get output: echo and print .

What is PHP output buffering?

Output buffering is a mechanism for controlling how much output data (excluding headers and cookies) PHP should keep internally before pushing that data to the client. If your application's output exceeds this setting, PHP will send that data in chunks of roughly the size you specify.

Why use ob_ start in PHP?

The ob_start() function creates an output buffer. A callback function can be passed in to do processing on the contents of the buffer before it gets flushed from the buffer. Flags can be used to permit or restrict what the buffer is able to do.

What is ob_ start() and ob_ end_ flush() in PHP?

While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush().


1 Answers

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
like image 199
Wes Mason Avatar answered Oct 25 '22 08:10

Wes Mason