Marty Wallace
Marty Wallace

Reputation: 35734

PHP get output stream or just echo

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');

Upvotes: 8

Views: 15437

Answers (4)

Venkat Papana
Venkat Papana

Reputation: 4927

Here php://stdout is not buffered stream, fwrite can buffer the output using php://output

Upvotes: 1

Brad Koch
Brad Koch

Reputation: 20267

In addition to the already noted technical difference, there's also the obvious difference in style and convention. echo/print is the normal way of producing output in PHP; writing to output as if to a file would be abnormal and potentially confusing. For the sake of the clarity of your intent, I wouldn't advise doing this unless you have a good reason to do so.

Upvotes: 1

Daniel M
Daniel M

Reputation: 3379

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

Upvotes: 3

Chris Trahey
Chris Trahey

Reputation: 18290

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.

Upvotes: 11

Related Questions