你可以在 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";
?>