15

When writing a large chunk to STDOUT in PHP you can do this:

echo <<<END_OF_STUFF
lots and lots of text
over multiple lines
etc.etc
END_OF_STUFF;

(i.e. heredoc)

I have the need to do a similar thing but to STDERR. Is there another command like echo but uses STDERR instead?

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • What _exactly_ do you want to do? And what have you tried doing? – Naftali Aug 20 '12 at 14:32
  • 2
    Perhaps this post will help you - http://stackoverflow.com/a/554775/558021. Just write to `php://stderr` – Lix Aug 20 '12 at 14:32
  • 1
    I was hoping for the moral equilivant of `echo` but works on `STDERR` instead. – Ed Heal Aug 20 '12 at 14:40
  • An echo is an echo - it all depends where you place it. You could write your own custom `"error_echo()"` function... – Lix Aug 20 '12 at 14:41

3 Answers3

24

For a simple solution - try this

file_put_contents('php://stderr', 'This text goes to STDERR',FILE_APPEND);

The FILE_APPEND parameter will append data and not overwrite it. You could also write directly to the error stream using the fopen and fwrite functions.

More info can be found at - http://php.net/manual/en/features.commandline.io-streams.php

Lix
  • 47,311
  • 12
  • 103
  • 131
21

Yes, using php:// stream wrapper: http://php.net/manual/en/wrappers.php.php

$stuff = <<<END_OF_STUFF
lots and lots of text
over multiple lines
etc.etc
END_OF_STUFF;

$fh = fopen('php://stderr','a'); //both (a)ppending, and (w)riting will work
fwrite($fh,$stuff);
fclose($fh);
Mchl
  • 61,444
  • 9
  • 118
  • 120
  • 15
    Instead of the `fopen` stuff I just used `fwrite(STDERR, $stuff);` - Was hoping not to have to create variables all the time. – Ed Heal Aug 20 '12 at 14:46
  • 12
    You don't need to open the error stream. [It is already opened and assigned to the constant `STDERR`.](http://php.net/manual/en/features.commandline.io-streams.php) – Lix Aug 20 '12 at 14:48
  • 7
    That's correct, but assuming we're in CLI, which is not explicitly given in question :) – Mchl Aug 20 '12 at 17:04
2

In the CLI SAPI, it can be as simple as passing a Heredoc string as an argument to fwrite() with the STDERR constant.

fwrite(STDERR, <<< EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD
);
Keith Shaw
  • 624
  • 6
  • 7