How to handle stdin for stdout in php?

I am trying to write a simple php script to take data from stdin , process it, and then write it to stdout . I know that PHP is probably not the best language for this kind of thing, but there is existing functionality that I need.

I tried

 <?php $file = file_get_contents("php://stdin", "r"); echo $file; ?> 

but that will not work. I call it this way: echo -e "\ndata\n" | PHP .php | cat echo -e "\ndata\n" | PHP .php | cat echo -e "\ndata\n" | PHP .php | cat . and do not receive error messages. The script I'm trying to build will, in fact, be part of a larger pipeline.

Any clues as to why this is not working?

PS: I am not very good at PHP.

+4
source share
3 answers

If you use a pipeline, you will need to buffer the input, rather than process it all at once, just go one line at a time, as is standard with * nix tools.

SheBang on top of the file allows you to directly execute the file, instead of calling php on the command line.

Save the following for test.php and run

 cat test.php | ./test.php 

to see the results.

 #!php <?php $handle = fopen('php://stdin', 'r'); $count = 0; while(!feof($handle)) { $buffer = fgets($handle); echo $count++, ": ", $buffer; } fclose($handle); 
+5
source

To put php script in a channel you can use:

 xargs -d "\n" ./mysrcipt.php --foo 

With many lines, /args./myscript.php will be called a couple of times, but always with --foo.

eg:.

 ./myscript.php: #!/bin/php <?php foreach($args as $key => $value){ echo "\n".$key.":".$value; } ?> cat -n1000 /path/file | xargs -d "\n" ./myscript.php --foo | less 

will invoke the script twice with an echo in stdout / less:

 0:./myscript 1:--foo 2:[file-line1] 3:[file-line2] ... 800:[file-line799] 0:./myscript 1:--foo 2:[file-line800] ... 

a source

+3
source

That's right, it works.

 <?php $input_stream = fopen("php://stdin","r"); $text=""; while($line = fgets($input_stream,4096)){ // Note 4k lines, should be ok for most purposes $text .= $line; } fclose($input_stream); print($text); ?> 

from the recipe for PHPBuilder .

0
source

Source: https://habr.com/ru/post/1315704/


All Articles