php 从 STDIN 逐行读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11968244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:32:26  来源:igfitidea点击:

Reading line by line from STDIN

phppipestdin

提问by sobi3ch

I want to do something like this:

我想做这样的事情:

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

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

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

回答by Shiplu Mokaddim

use STDINconstant as file handler.

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

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

Note: fgets on STDIN reads the \ncharacter.

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

回答by Luis Colón

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

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

Requires PHP 5 >= 5.5.0, PHP 7

需要 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

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