php 处理<来自命令行的文件输入

php handling < file input from command line

我知道我可以通过这样的命令 line/shell 脚本接收参数:

!#/usr/bin/php
<?php
# file name - process.php
print_r($argv);

但是重定向如下:

#> ./process.php < input.txt

如何读取文件,input.txt 是字符串参数还是已经创建的某种类型的文件指针?

Read from STDIN 与 C:

非常相似
<?php
$stdin = fopen('php://stdin', 'r');
// Get the whole file, line by line:
while (($line = fgets($stdin)) !== FALSE) {
    ...
}
?>

如果您希望将整个文件内容放入一个变量中,有一个快捷方式:

$contents = stream_get_contents(STDIN);

Oliver,您应该 post 一个不同的答案,而不是修改用户的 post。这是您想要 post:

#!/usr/bin/php -q
<?php
    //NOTE the -q switch in hashbang above, silences MIME type output when reading the file!
    $stdin = fopen('php://stdin', 'r');
    // Get the whole file, line by line:
    while (($line = fgets($stdin)) !== FALSE) {
        ...
    }
?>