如何从CLI标准输入中读取非ASCII字符 [英] How to read non-ASCII characters from CLI standard input
问题描述
如果在CMD中键入å
,则fgets将停止等待更多输入,并且循环将一直运行,直到按 ctrl-c
。如果我输入a-z0-9 !!()之类的正常字符,则按预期工作。
If I type å
in CMD, fgets stop waiting for more input and the loop runs until I press ctrl-c
. If I type a "normal" characters like a-z0-9!?() it works as expected.
我在Windows 7下使用UTF-在CMD中运行代码8作为字符集( chcp 65001
),该文件另存为UTF-8,没有bom。我使用PHP 5.3.5(cli)。
I run the code in CMD under Windows 7 with UTF-8 as charset (chcp 65001
), the file is saved as UTF-8 without bom. I use PHP 5.3.5 (cli).
<?php
echo "ÅÄÖåäö work here.\n";
while(1)
{
echo '> '. fgets(STDIN);
}
?>
如果我将字符集更改为 chcp 1252
输入å
并打印出>å时循环不会中断,但ÅÄÖåäö在这里工作变成ÅÄ Öåäö¶在这里工作!。而且我知道我可以将文件更改为ANSI,但是然后我不能使用诸如╠╦╗这样的特殊字符。
If I change charset to chcp 1252
the loop doesn't break when I type å
and it print "> å" but the "ÅÄÖåäö work here" become "ÅÄÖåäö work here!". And I know that I can change the file to ANSI, but then I can't use special characters like ╠╦╗.
所以fgets为什么停止等待
如何输入用户名?我该如何解决?
编辑:
还发现了一个奇怪的错误。
echoöäåÅÄÖÖääöwork here!or?。chr(10);
-> äåÅÄÖÖääöhere!要么?回覆!还是?
。
如果echo中的第一个字符为å/ä/ö
,则会打印出奇怪的字符,并且最终输出重复项的 n-1
字符。(n =字符串开头的åäö数)。
Also found a strange bug.
echo "öäåÅÄÖåäö work here! Or?".chr(10);
-> ��äåÅÄÖåäö work here! Or? re! Or?
.
If the first char in echo is å/ä/ö
it print strange chars AND the end output duplicate's with n - 1
char.. (n = number of åäö in the begining of the string).
例如: echoåäö1234 -> ?? 123434
和 echoåäöåäö1234
-> ?äöåäö1234 1234
。
EDIT2(已解决):
问题是 chcp 65001
,现在我使用 chcp 437
( chcp 437 )。
非常感谢Timothy Martens!
The problem was chcp 65001
, now I use chcp 437
(chcp 437).
Big thanks to Timothy Martens!
推荐答案
可能的解决方案:
echo '>';
$line = stream_get_line(STDIN, 999999, PHP_EOL);
注意:
我无法使用多个版本的PHP重现您的错误。
使用以下PHP版本5.3.8没有任何问题
Notes: I was unable to reproduce your error using multiple versions of PHP. Using the following PHP version 5.3.8 gave me no issues
PHP 5.3(5.3.8)
VC9 x86 Non Thread Safe(2011-Aug-23 12:26:18)
Arcitechture是Win XP SP3 32位
PHP 5.3 (5.3.8) VC9 x86 Non Thread Safe (2011-Aug-23 12:26:18) Arcitechture is Win XP SP3 32 bit
您可以尝试升级PHP。
You might try upgrading PHP.
我下载了php-5.3.5-nts-Win32-VC6-x86,但无法重现错误,对我来说效果很好
I downloaded php-5.3.5-nts-Win32-VC6-x86 and was not able to reproduce your error, it works fine for me.
编辑:另外,我使用西班牙语键盘输入字符。
Additionaly I typed the characters using my spanish keyboard.
Edit2:
CMD命令:
chcp 437
PHP代码:
<?php
$fp=fopen("php://stdin","r");
while(1){
$str = fgets(STDIN);
echo mb_detect_encoding($str)."\n";
echo '>'.stream_get_line($fp,999999,"\n")."\n";
}
?>
输出:
test
ASCII
test
>test
öïü
öïü
>öïü
这篇关于如何从CLI标准输入中读取非ASCII字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!