How to print a line to STDERR and STDOUT in PHP?

In PHP, how to print a string as a line to STDOUT? That is, the string and the newline character, nicely?

And similarly, how to print the line to STDERR?

In PHP, you may print a line to STDOUT using echo by appending the PHP_EOL to the string:

echo $your_msg . PHP_EOL;

For example,

$ php -a
Interactive shell

php > echo "hello world!" . PHP_EOL;
hello world!
php > 

To print to STDERR, you may use fwrite like

fwrite(STDERR, "hello, world!" . PHP_EOL);

One example is as follows.

$ cat php-stderr.php 
fwrite(STDERR, "hello, world!" . PHP_EOL);

$ php php-stderr.php 2>/tmp/stderr
$ cat /tmp/stderr 
hello, world!
Leave a Reply

Your email address will not be published. Required fields are marked *