How to process stdin to stdout in php?

19,071

Solution 1

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

Solution 2

To place a php-script in a pipe you can use:

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

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

e.g.:

./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 call the script two times with echo to stdout/less:

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

source

Share:
19,071

Related videos on Youtube

brice
Author by

brice

I am a software engineer and entrepreneur living and working in the UK. I'm interested in Functional, Dataflow, and Functional-reactive programming, polyglot frameworks and data-centric design. You can find out more on github, or on twitter @fractallambda The many pow()s of Python AES in C and Java Reading from Mongo, processing with Hadoop, writing to SQL Memory allocation in C and source material for answer Sending raw Ethernet frames with Python

Updated on June 04, 2022

Comments

  • brice
    brice almost 2 years

    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.

  • brice
    brice almost 14 years
    thanks compie. I can't afford to have the initial stream bisected as xargs would do. The php script has to have the entire thing. Is there really no way of using php in a pipe without resorting to stuff like this?
  • CMCDragonkai
    CMCDragonkai over 10 years
    What if there is no STDIN available at the time of execution? Wouldn't this make the script hang?
  • Kamafeather
    Kamafeather almost 5 years
    I just assume that the STDIN is always available in PHP, but its buffer will be empty (or, better, just including EOF).

Related