How to use STDOUT in php

PhpCommand Line

Php Problem Overview


I am running into a project that read a stream from a txt file, so in the CLI, i write:

cat texte.txt|php index.php

In my index.php file i read the stream:

$handle = fopen ("php://stdin","r");

Now i have a $result that contains the result of my processing file and i want to output it with STDOUT, I looked in the manual, but I don't know how to use it, can you please make me a use example.

Php Solutions


Solution 1 - Php

Okay, let me give you another example for the STDIN and STDOUT usage.

In PHP you use these two idioms:

 $input = fgets(STDIN);

 fwrite(STDOUT, $output);

When from the commandline you utilize them as such:

 cat "input.txt"  |  php script.php   >  "output.txt"

 php script.php  < input.txt  > output.txt

 echo "input..."  |  php script.php   |  sort  |  tee  output.txt

That's all these things do. Piping in, or piping out. And the incoming parts will appear in STDIN, whereas your output should go to STDOUT. Never cross the streams, folks!

Solution 2 - Php

The constants STDIN and STDOUT are already resources, so all you need to do is

fwrite(STDOUT, 'foo');

See http://php.net/manual/en/wrappers.php

> php://stdin, php://stdout and php://stderr allow direct access to the corresponding input or output stream of the PHP process. The stream references a duplicate file descriptor, so if you open php://stdin and later close it, you close only your copy of the descriptor-the actual stream referenced by STDIN is unaffected. Note that PHP exhibited buggy behavior in this regard until PHP 5.2.1. It is recommended that you simply use the constants STDIN, STDOUT and STDERR instead of manually opening streams using these wrappers.

Solution 3 - Php

this should work for you

$out = fopen('php://output', 'w'); //output handler
fputs($out, "your output string.\n"); //writing output operation
fclose($out); //closing handler

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMallocView Question on Stackoverflow
Solution 1 - PhpmarioView Answer on Stackoverflow
Solution 2 - PhpGordonView Answer on Stackoverflow
Solution 3 - Phpuser336883View Answer on Stackoverflow