Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process stdin to stdout in php?

Tags:

php

stdout

stdin

I'm trying to write a simple php script to take in data from stdin, process it, 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've tried

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

but it doesn't work. I'm invoking it like this: echo -e "\ndata\n" | php script.php | cat. and get no error messages. The script I'm trying to build will actually be part of a larger pipeline.

Any clues as to why this is not working?

PS: I'm not very experienced with PHP.

like image 388
brice Avatar asked Jan 21 '23 18:01

brice


1 Answers

If you are piping, you will want to buffer the input, instead of processing it all at once, just go one line at a time as is standard for *nix tools.

The SheBang on top of the file allows you to execute the file directly, instead of having to call php in the command line.

Save the following to 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);
like image 166
tylermac Avatar answered Jan 29 '23 16:01

tylermac