Printing to the terminal when using output buffering in PHP CLI scripts

I use the PHP command line to create some files offline. To write the output of the script, I use the standard ob_start object:

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 on the terminal (for example, warnings), collecting the "main output" in the buffer. Is there any way to do this? It does not seem to be possible to temporarily suspend buffering to print terminal messages, and then continue buffering from where it was left. Is there a workaround for this?

+6
command-line php
source share
3 answers

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

 ob_start(); echo 'Output buffer'; fputs(STDOUT, "Log message"); $x = ob_get_contents(); ob_end_clean();; echo "X = $x"; 
+8
source share

Use php://stderr stream:

 $f = fopen('php://stderr', 'w'); fputs($f, 'Output'); 

EDIT: In addition, the CLI has a predefined constant STDERR :

 fputs(STDERR, 'Output'); 
+5
source share

You can pause the output buffer. Write the contents of the buffer to a variable and end the buffer without flushing. Write some unbuffered output and call ob_start () again. This method uses string concatenation, and it is a relatively dirty method. For this reason, I prefer other methods above mine.

But in any case, here is a small working example:

 <?php ob_start(); echo 'Buffered line 1.<br>'; $ob = ob_get_contents(); ob_end_clean(); echo 'Non-buffered line.<br>'; ob_start(); echo 'Buffered line 2.<br>'; $ob .= ob_get_contents(); ob_end_clean(); echo 'Non-buffered line.<br>'; ob_start(); echo 'Buffered line 3.<br>'; $ob .= ob_get_contents(); ob_end_clean(); echo 'Non-buffered line.<br>'; echo $ob; ?> 
+2
source share

All Articles