从STDIN逐行读取


Reading line by line from STDIN

我想做这样的事情:

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

parse_STDIN.php文件中,我希望能够从 stdin 逐行解析我的数据。

使用STDIN常量作为文件处理程序。

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

注意:STDIN 上的 fgets 读取'n字符。

你也可以使用生成器 - 如果你不知道STDIN会有多大。

需要 PHP 5>= 5.5.0, PHP 7

大致如下:

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

您可以在此处阅读有关生成器的更多信息(或谷歌搜索教程):http://php.net/manual/en/language.generators.overview.php