欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php iconv() : Detected an illegal character in input string

程序员文章站 2022-07-11 08:05:41
开始是这样用的$str = iconv('utf-8', 'gb2312', unescape(isset($_get['str'])? $_get['str']:''))...
开始是这样用的
$str = iconv('utf-8', 'gb2312', unescape(isset($_get['str'])? $_get['str']:''));
上线后报一堆这样的错:iconv() : detected an illegal character in input string

考虑到gb2312字符集比较小,换个大的吧,于是改成gbk:
$str = iconv('utf-8', 'gbk', unescape(isset($_get['str'])? $_get['str']:''));
上线后还是报同样的错!

再认真读手册,发现有这么一段:
if you append the string //translit to out_charset transliteration is activated. this means that when a character can't be represented in the target charset, it can be approximated through one or several similarly looking characters. if you append the string //ignore, characters that cannot be represented in the target charset are silently discarded. otherwise, str is cut from the first illegal character.
于是改成:
$str = iconv('utf-8', 'gbk//ignore', unescape(isset($_get['str'])? $_get['str']:''));
本地测试//ignore能忽略掉它不认识的字接着往下转,并且不报错,而//translit是截掉它不认识的字及其后面的内容,并且报错。//ignore是我需要的。
现在等待上线看结果(这样不是好的做法,继续琢磨手册,上网搜搜看),呵呵。。。

在网上找到下面这篇文章,发现mb_convert_encoding也可以,但效率比iconv差。


转换字符串编码iconv与mb_convert_encoding的区别

iconv — convert string to requested character encoding(php 4 >= 4.0.5, php 5)
mb_convert_encoding — convert character encoding(php 4 >= 4.0.6, php 5)

用法:
string mb_convert_encoding ( string str, string to_encoding [, mixed from_encoding] )
需要先启用 mbstring 扩展库,在 php.ini里将; extension=php_mbstring.dll 前面的 ; 去掉

string iconv ( string in_charset, string out_charset, string str )
注意:
第二个参数,除了可以指定要转化到的编码以外,还可以增加两个后缀://translit 和 //ignore,
其中:
//translit 会自动将不能直接转化的字符变成一个或多个近似的字符,
//ignore 会忽略掉不能转化的字符,而默认效果是从第一个非法字符截断。
returns the converted string or false on failure.

使用:
1. 发现iconv在转换字符"-"到gb2312时会出错,如果没有ignore参数,所有该字符后面的字符串都无法被保存。不管怎么样,这个"-"都无法转换成功,无法输出。另外mb_convert_encoding没有这个bug.
2. mb_convert_encoding 可以指定多种输入编码,它会根据内容自动识别,但是执行效率比iconv差太多;如:$str = mb_convert_encoding($str,"euc-jp","ascii,jis,euc-jp,sjis,utf- 8");“ascii,jis,euc-jp,sjis,utf-8”的顺序不同效果也有差异
3. 一般情况下用 iconv,只有当遇到无法确定原编码是何种编码,或者iconv转化后无法正常显示时才用mb_convert_encoding 函数

from_encoding is specified by character code name before conversion. it can be array or string - comma separated enumerated list. if it is not specified, the internal encoding will be used.

$str = mb_convert_encoding($str, "ucs-2le", "jis, eucjp-win, sjis-win");
$str = mb_convert_encoding($str, "euc-jp', "auto");

例子:
$content = iconv("gbk", "utf-8", $content);
$content = mb_convert_encoding($content, "utf-8", "gbk");