Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get output stream or just echo

Tags:

php

What would be the differnce in php command line app of just echoing or printf etc some string as opposed to getting sdtout stream and writing to it i.e.

$stdout = fopen('php://stdout', 'w');
like image 254
Marty Wallace Avatar asked Aug 25 '12 19:08

Marty Wallace


2 Answers

The first thing that comes to mind for me is output buffering. echo and print interface with the output buffering mechanism, but directly writing to stdout bypasses it.

Consider this script:

<?php
$stdout = fopen('php://stdout', 'w');
ob_start();
        echo "echo output\n";
        fwrite($stdout, "FWRITTEN\n");
        echo "Also echo\n";
$out = ob_get_clean();
echo $out;

which outputs:

FWRITTEN
echo output
Also echo

which demonstrates that echo is buffered, and fwrite is not.

like image 74
Chris Trahey Avatar answered Sep 21 '22 01:09

Chris Trahey


The difference is that echo writes to php://output which is the output buffer stream. However, php://stdout gives you direct access to the processes' output stream which is unbuffered.

Further information regarding streams can be found in the manual: http://www.php.net/manual/en/wrappers.php.php

like image 20
Daniel M Avatar answered Sep 18 '22 01:09

Daniel M