您可以在 Unix 系统上打开 /dev/tty 或在 Windows 上打开 \con,并使用 ob_implicit_flush(true) 来非缓冲地写入输出。非常有效 :-)
-------------------------------
#!/usr/local/bin/php -q
<?php
set_time_limit(0);
@ob_end_flush();
ob_implicit_flush(true);
class prompt {
var $tty;
function prompt() {
if (substr(PHP_OS, 0, 3) == "WIN") {
$this->tty = fOpen("\con", "rb");
} else {
if (!($this->tty = fOpen("/dev/tty", "r"))) {
$this->tty = fOpen("php://stdin", "r");
}
}
}
function get($string, $length = 1024) {
echo $string;
$result = trim(fGets($this->tty, $length));
echo "\n";
return $result;
}
}
echo "输入内容或输入 'exit' 退出\n";
do {
$cmdline = new prompt();
$buffer = $cmdline->get("请输入内容: ");
echo "你输入了: $buffer\n";
} while ($buffer !== "exit");
echo "再见\n";
?>