如何编写命令行交互式PHP脚本?

use*_*841 19 php shell

我想编写一个可以从命令行使用的PHP脚本.我希望它提示并接受一些项目的输入,然后吐出一些结果.我想在PHP中执行此操作,因为我的所有类和库都在PHP中,我只想创建一个简单的命令行界面来处理一些事情.

提示和接受重复的命令行输入是绊倒我的部分.我该怎么做呢?

Jus*_*ier 19

PHP手册中的I/O Streams页面描述了如何使用STDIN从命令行读取一行:

<?php
 $line = trim(fgets(STDIN)); // reads one line from STDIN
 fscanf(STDIN, "%d\n", $number); // reads number from STDIN
?>
Run Code Online (Sandbox Code Playgroud)


aio*_*obe 15

PHP:从键盘读取 - 通过键入来从键盘控制台获取用户输入:

您需要一个特殊文件:php://stdin代表标准输入.

print "Type your message. Type '.' on a line by itself when you're done.\n";

$fp = fopen('php://stdin', 'r');
$last_line = false;
$message = '';
while (!$last_line) {
    $next_line = fgets($fp, 1024); // read the special file to get the user input from keyboard
    if (".\n" == $next_line) {
      $last_line = true;
    } else {
      $message .= $next_line;
    }
}
Run Code Online (Sandbox Code Playgroud)


Tim*_*ost 10

我不确定您的输入有多复杂,但readline是处理交互式CLI程序的绝佳方式.

您可以获得与shell相同的生物舒适度,例如命令历史记录.

使用它很简单:

$command = readline("Enter Command: ");
/* Then add the input to the command history */
readline_add_history($command);
Run Code Online (Sandbox Code Playgroud)

如果可用,它确实使它变得简单.


这是控制台实现的典型案例:

do {
  $cmd = trim(strtolower( readline("\n> Command: ") ));
  readline_add_history($cmd);
  switch ($cmd) {
    case 'hello': print "\n -- HELLO!\n"; break;
    case 'bye': break;
    default: print "\n -- You say '$cmd'... say 'bye' or 'hello'.\n";
  }
} while ($cmd!='bye');
Run Code Online (Sandbox Code Playgroud)

用户可以使用箭头(向上和向下)访问历史记录.