6

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?

3 Answers 3

8

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";
Sign up to request clarification or add additional context in comments.

Comments

6

Use the php://stderr stream:

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

EDIT: Also, in CLI, there is a predefined STDERR constant:

fputs(STDERR, 'Output');

Comments

2

It is possible to 'pause' an output buffer. Write the contents of the buffer to a variable, and end the buffer without flushing. Write some non-buffered output, and call ob_start() again. This method uses string concatenation, and it's a relatively dirty method. I prefer the other methods above my own for this reason.

But in either case, here's 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;
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.