Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing to terminal while using output buffering in CLI PHP scripts

I'm using command line PHP to build some files offline. To capture the script output I use the standard ob_start stuff:

ob_start();
// Echo lots of stuff
$content = ob_get_contents();
// Now the $content can be written to a file

However, I also want to print some messages to the terminal (for instance, warnings) while collecting the "main output" into the buffer. Is there a way to do this? It doesn't seem to be possible to pause the buffering for a while to print the terminal messages, and then continue the buffering from where it was left. Is there any workaround for this?

like image 268
Joonas Pulakka Avatar asked Aug 31 '09 07:08

Joonas Pulakka


1 Answers

Just write to STDOUT or STDERR (both constants containing file pointer resources) using fputs():

ob_start();
echo 'Output buffer';
fputs(STDOUT, "Log message");
$x = ob_get_contents();
ob_end_clean();;

echo "X = $x";
like image 118
NSSec Avatar answered Nov 12 '22 17:11

NSSec