Malloc
Malloc

Reputation: 16256

How to use STDOUT in php

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.

Upvotes: 57

Views: 148104

Answers (3)

mario
mario

Reputation: 145472

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!

Upvotes: 69

Gordon
Gordon

Reputation: 316939

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.

Upvotes: 34

user336883
user336883

Reputation:

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

Upvotes: 29

Related Questions