Reading line by line from STDIN

前端 未结 2 2016
情深已故
情深已故 2020-12-08 18:15

I want to do something like this:

$ [mysql query that produces many lines] | php parse_STDIN.php

In parse_STDIN.php file I wan

相关标签:
2条回答
  • 2020-12-08 18:55

    use STDIN constant as file handler.

    while($f = fgets(STDIN)){
        echo "line: $f";
    }
    

    Note: fgets on STDIN reads the \n character.

    0 讨论(0)
  • 2020-12-08 19:00

    You could also use a generator - if you don't know how large the STDIN is going to be.

    Requires PHP 5 >= 5.5.0, PHP 7

    Something along the lines of:

    function stdin_stream()
    {
        while ($line = fgets(STDIN)) {
            yield $line;
        }
    }
    
    foreach (stdin_stream() as $line) {
        // do something with the contents coming in from STDIN
    }
    

    You can read more about generators here (or a google search for tutorials): http://php.net/manual/en/language.generators.overview.php

    0 讨论(0)
提交回复
热议问题