在 CLI 中僅使用 PHP 從使用者取得輸入的最佳且最簡單的方法是將 fgetc() 函式與 STDIN 常數一起使用
<?php
echo '您確定要退出嗎? (y/n) ';
$input = fgetc(STDIN);
if ($input == 'y')
{
exit(0);
}
?>
(PHP 4, PHP 5, PHP 7, PHP 8)
fgetc — 從檔案指標取得字元
返回一個字串,其中包含從 stream
指向的檔案中讀取的單個字元。到達檔案結尾 (EOF) 時返回 false
。
範例 #1 fgetc() 範例
<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
echo '無法開啟檔案 somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
echo "$char\n";
}
?>
注意:此函式是二進位安全的。
在 CLI 中僅使用 PHP 從使用者取得輸入的最佳且最簡單的方法是將 fgetc() 函式與 STDIN 常數一起使用
<?php
echo '您確定要退出嗎? (y/n) ';
$input = fgetc(STDIN);
if ($input == 'y')
{
exit(0);
}
?>
我正在使用命令列 PHP 建立一個互動式腳本,希望使用者只輸入一個字元來回應「是/否」問題。我嘗試使用 fgets()、fgetc()、readline()、popen() 等各種建議方法,但都遇到了一些困難。最後想出了以下這個效果相當不錯的解決方法:
$ans = strtolower( trim( `bash -c "read -n 1 -t 10 ANS ; echo \\\$ANS"` ) );
要在 CLI 模式下讀取單個按鍵,您可以使用 ncurses(這可能需要 PHP 的額外模組)或使用 *nix 的 "/bin/stty" 命令(這方法比較 tricky)。
<?php
function stty($options) {
exec($cmd = "/bin/stty $options", $output, $el);
$el AND die("exec($cmd) 失敗");
return implode(" ", $output);
}
function getchar($echo = false) {
$echo = $echo ? "" : "-echo";
# 取得原始設定
$stty_settings = preg_replace("#.*; ?#s", "", stty("--all"));
# 設定新的設定
stty("cbreak $echo");
# 讀取字元直到輸入句點 (.) 為止,
# 並顯示其十六進位序数值。
printf("> ");
do {
printf("%02x ", ord($c = fgetc(STDIN)));
} while ($c != '.');
# 恢復設定
stty($stty_settings);
}
getchar();
?>
你不能簡單地像這樣逐字元印出以多位元組字元集編碼的文字;
因為 fgetc() 會將每個多位元組字元拆分成個別的位元組。參考以下範例:
<?php
$path = 'foo/cyrillic.txt';
$handle = fopen($path, 'rb');
while (FALSE !== ($ch = fgetc($handle))) {
$curs = ftell($hanlde);
print "[$curs:] $ch\n";
}
/* 執行結果類似如下:
<
[1]: <
[2]: h
[3]: 2
[4]: >
[5]: �
[6]: �
[7]: �
[8]: �
[9]: �
[10]: �
[11]:
[12]: �
[13]: �
[14]: �
[15]: �
[16]: �
*/ ?>
我認為這不是最好的方法,但可以作為一種解決方案。
<?php
$path = 'path/to/your/file.ext';
if (!$handle = fopen($path, 'rb')) {
echo "無法開啟 ($path) 檔案';
exit;
}
$mbch = ''; // 儲存雙位元組斯拉夫字母的第一個位元組
while (FALSE !== ($ch = fgetc($handle))) {
//檢查雙位元組斯拉夫字母的標記
if (empty($mbch) && (FALSE !== array_search(ord($ch), Array(208,209,129)))) {
$mbch = $ch; // 儲存第一個位元組
continue;
}
$curs = ftell($handle);
print "[$curs]: " . $mbch . $ch . PHP_EOL;
// 或 print "[$curs]: $mbch$ch\n";
if (!empty($mbch)) $mbch = ''; // 使用後清除位元組
}
?>