【问题标题】:How to use end of line character in php on command line?如何在命令行的php中使用行尾字符?
【发布时间】:2014-04-04 01:49:33
【问题描述】:

我希望使用 php 读取命令行并将它们写入文件。但是,当我运行以下命令时,如果命令行为空,则 while 循环不会返回。这应该如何修改?

#!/usr/bin/php
<?php
$file = fopen("/tmp/test", "a");
fwrite($file, "Script successfully ran at ".date("Y-m-d H:i:s")."\n");

// read from stdin
$fd = fopen("php://stdin", "r");
$output = "";
while (!feof($fd)) {
    $line = fread($fd, 1024);
    $output .= $line;
}
fclose($fd);

fwrite($file, $output);
fclose($file);
?>

【问题讨论】:

  • 我想你可以发送 Ctrl + Z.
  • 即使您输入一堆随机键或输入任何一个,while 循环也不会结束。
  • 我尝试了 \n, \r, 的组合。他们不工作
  • 要输入EOF,请按Ctrl+D。如果 EOF 不是单独出现在一行上,则需要输入两次。
  • 太棒了!我在新线路上做了Ctrl+D,它起作用了

标签: php bash shell command-line-arguments


【解决方案1】:

control-c 会导致 test.php 退出

使用stream_set_blocking(),见:http://us3.php.net/manual/en/function.stream-set-blocking.php

在你得到 $fd 之后调用 stream_set_blocking($fd, 1)

要将您在标准输入上输入的字符写入 $file,您需要在 while 循环内执行 fwrite,而不是在达到 feof 之后。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-01
    • 2011-09-25
    • 1970-01-01
    • 2012-06-01
    • 2020-07-12
    • 1970-01-01
    • 2010-11-25
    • 2013-05-09
    相关资源
    最近更新 更多