tags:

views:

1170

answers:

2

The code below almost works, but it's not what I really meant:

ob_start();
echo 'xxx';
$contents = ob_get_contents();
ob_end_clean();
file_put_contents($file,$contents);

Is there a more natural way?

+5  A: 

No, output buffering is as good as it gets. Though it's slightly nicer to just do

ob_start();
echo 'xxx';
$contents = ob_get_flush();
file_put_contents($file,$contents);
chaos
doesn't ob_get_flush() also send the buffer contents to the browser? maybe ob_get_clean() would be better.
Tom Haigh
No, that's ob_end_flush().
chaos
Is there a way to also get STDERR?
xer0x
I'm afraid not.
chaos
+2  A: 

It is possible to write STDOUT directly to a file in PHP, which is much easier and more straightforward than using output bufferering.

Do this in the very beginning of your script:

fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
$STDIN = fopen('/dev/null', 'r');
$STDOUT = fopen('application.log', 'wb');
$STDERR = fopen('error.log', 'wb');

Why at the very beginning you may ask? No file descriptors should be opened yet, because when you close the standard input, output and error file descriptors, the first three new descriptors will become the NEW standard input, output and error file descriptors.

In my example here I redirected standard input to /dev/null and the output and error file descriptors to log files. This is common practice when making a daemon script in PHP.

To write to the application.log file, this would suffice:

echo "Hello world\n";

To write to the error.log, one would have to do:

fwrite($STDERR, "Something went wrong\n"); 
Bas Peters