Easiest way to redirect PHP output to a text file

What is the easiest way to redirect the output of a PHP script to a text file as the output is generated?

I would use fwrite()

Okay, but how would I go about using this function to write the output to a file AS the output is generated?

If the script fails and ends unexpectedly, I still want all of the output generated before that point to be written to a file.

it depends on the type and how the output is generated.

You haven’t specified either.

The idea is to have ANY output which would be sent to the browser to be written to a text file as the output is generated.

In other words, all data sent to STDOUT needs to be redirected or copied to a text file as the data is sent.

A command line cannot be used in this situation.

Something like:


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

file_put_contents('file.txt', $content);

Or, you can register a callback with [fphp]ob_start/fphp and save as you go. :slight_smile:

It seems the script doesn’t finish because the text file is never created.

If I replace the include line with a simple echo, it works just fine.
This would lead me to believe the included script contained a fatal error, however, no fatal errors are reported in the error log.
(error_reporting is set to E_ALL at the start of the included script)

Ah if you’re trying to capture errors as well, you can either use eval() or run it through a web server and save final output:


file_put_contents('file.txt', file_get_contents('http://url/file.php'));

Another alternative is:


exec ('php file.php', $output);
file_put_contents('file.txt', $output);