有20种类型的中文编码:
中国EUC-CN,HZ,GBK,CP936,GB18030,EUC-TW,BIG5,CP950, BIG5-HKSCS,BIG5-HKSCS:2004,BIG5-HKSCS:2001,BIG5-HKSCS:1999, ISO-2022-CN,ISO-2022-CN-EXT
所以我有一个不是UTF-8的文本文件。这是ASCII。我想使用iconv()
将其转换为UTF-8。但为此我需要知道源的字符编码。
如果我不懂中文,我怎么能这样做? :(
我注意到了:
$str = iconv('GB18030', 'UTF-8', $str);
file_put_contents('file.txt', $str);
生成UTF-8编码文件,而我尝试过的其他编码(CP950,GBK和EUC-CN)生成了一个ASCII文件。这是否意味着iconv
能够检测给定字符串的输入编码是否错误?
答案 0 :(得分:3)
这可能可以满足您的需求(但我真的不知道)。设置语言环境和utf8_decode,并使用mb_check_encoding
而不是mt_detect_encoding似乎提供了一些有用的输出..
// some text from http://chinesenotes.com/chinese_text_l10n.php
// have tried both as string and content loaded from a file
$chinese = '譧躆 礛簼繰 剆坲姏 潧 騔鯬 跠 瘱瘵瘲 忁曨曣 蛃袚觙';
$chinese=utf8_decode($chinese);
$chinese_encodings ='EUC-CN,HZ,GBK,CP936,GB18030,EUC-TW,BIG5,CP950,BIG5-HKSCS,BIG5-HKSCS:2004,BIG5-HKSCS:2001,BIG5-HKSCS:1999,ISO-2022-CN,ISO-2022-CN-EXT';
$encodings = explode(',',$chinese_encodings);
//set chinese locale
setlocale(LC_CTYPE, 'Chinese');
foreach($encodings as $encoding) {
if (@mb_check_encoding($chinese, $encoding)) {
echo 'The string seems to be compatible with '.$encoding.'<br>';
} else {
echo 'Not compatible with '.$encoding.'<br>';
}
}
输出
The string seems to be compatible with EUC-CN
The string seems to be compatible with HZ
The string seems to be compatible with GBK
The string seems to be compatible with CP936
Not compatible with GB18030
The string seems to be compatible with EUC-TW
The string seems to be compatible with BIG5
The string seems to be compatible with CP950
Not compatible with BIG5-HKSCS
Not compatible with BIG5-HKSCS:2004
Not compatible with BIG5-HKSCS:2001
Not compatible with BIG5-HKSCS:1999
Not compatible with ISO-2022-CN
Not compatible with ISO-2022-CN-EXT
总猜。现在它至少似乎认识到了一些中国编码。如果它是完全垃圾则删除。
答案 1 :(得分:2)
我对中文编码没有经验,我知道这个问题被标记为iconv
,但如果它能完成工作,那么您可以尝试mb_detect_encoding来检测您的编码;第二个参数是要检查的编码列表,并且有一个关于中文编码的用户制作的评论:
对于中国开发者:请注意第二个论点 功能不包括'GB2312'和'GBK',返回值为 'EUC-CN'当被检测为GB2312字符串时。
所以,如果您明确提供中文编码的完整列表作为第二个参数,它可能会有效吗?它可以像这样工作:
$encoding = mb_detect_encoding($chineseString, 'GB2312,GBK,(...)');
if($encoding) $utf8text = iconv($encoding, 'UTF-8', $str);
您可能还想玩第三个参数(strict
)
答案 2 :(得分:2)
难以检测编码的原因是八位字节序列在几种编码中解码为有效字符,但结果仅在正确的编码中才有意义。我在这些情况下所做的是获取解码后的文本,然后转到automatic translation service,看看你是否收到了清晰易读的文字或混乱的音节。
您可以通过编程方式执行此操作,例如通过分析输入文本中的三角频率。像this one这样的库已经被创建来解决这个问题,并且有外部程序可以做到这一点,但我还没有看到任何PHP API。但这种方法并非万无一失。