【问题标题】:php handling < file input from command linephp处理<从命令行输入的文件
【发布时间】:2017-01-11 16:01:03
【问题描述】:

我知道我可以像这样在命令行/shell 脚本上接收参数:

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

但是如下重定向呢:

#> ./process.php < input.txt

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

【问题讨论】:

    标签: php command-line-interface stdin


    【解决方案1】:

    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);
    

    【讨论】:

    • 非常简洁的答案。顺便说一句:shell 脚本中提到的&lt; 字符(和&gt;)是什么?
    • 它没有特定的名称 afaik 但 被称为重定向运算符。
    • 另外,我将 MIME 类型回显到 STDOUT(无论脚本中是否有任何编码)。 IE。 Content-type: text/html; charset=UTF-8 - 我该如何抑制这个?
    • @OliverWilliams 您的脚本(或者可能是库)中的某些内容正在设置 HTTP 标头。要抑制 CLI 上的标头输出,请使用 php -h 运行 PHP。
    • 马特我编辑了你的答案,哈希爆炸应该看起来像#!/usr/bin/php -q 来抑制这个。 Wild guess -q 代表安静;)
    【解决方案2】:

    Oliver,您应该发布不同的答案,而不是修改用户的帖子。这是您要发布的内容:

    #!/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) {
            ...
        }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      相关资源
      最近更新 更多