Reading line by line from STDIN

PhpPipeStdin

Php Problem Overview


I want to do something like this:

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

In parse_STDIN.php file I want to be able to parse my data line by line from stdin.

Php Solutions


Solution 1 - Php

use STDIN constant as file handler.

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

Note: fgets on STDIN reads the \n character.

Solution 2 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsobi3chView Question on Stackoverflow
Solution 1 - PhpShiplu MokaddimView Answer on Stackoverflow
Solution 2 - PhpLuis ColónView Answer on Stackoverflow