Reading line by line from STDIN

烈酒焚心 提交于 2019-11-28 21:02:20

use STDIN constant as file handler.

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

Note: fgets on STDIN reads the \n character.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!