不是iconv函数的bug

上一篇把题目写成《iconv函数的小bug》怪吓人的~~~华晨同学的回复使我感到自己的不求甚解.正所谓知错能改,善莫大焉。于是我重新查了一遍:php官方的说明:http://cn.php.net/manual/en/function.iconv.php
函数原型:string iconv ( string $in_charset , string $out_charset , string $str )
特别是第二个参数说明:
The output charset.

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 and an E_NOTICE is generated.

意思是如果你在第二个参数后面加上//TRANSLIT ,这样的话,当遇到目标输出的编码不认识的字符的时候,能被一个或几个近似的字符代替;而如果在第二个参数后面加上//IGNORE的时候,当目标输出的编码不认识的时候则什么也不操作;什么都不加的时候则会报错~~~

手册里面有个非常生动的例子:

<?php
$text = "This is the Euro symbol '€'.";
 
echo 'Original : ', $text, PHP_EOL;
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
echo 'IGNORE   : ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL;
echo 'Plain    : ', iconv("UTF-8", "ISO-8859-1", $text), PHP_EOL;
 
?>

输出结果是:

Original : This is the Euro symbol ‘€’.
TRANSLIT : This is the Euro symbol ‘EUR’.
IGNORE   : This is the Euro symbol ”.
Plain    :
Notice: iconv(): Detected an illegal character in input string in .\iconv-example.php on line 7
This is the Euro symbol ‘

这样就非常清楚了

这里总结几点教训:

第一:php最好的手册就是官方的在线收藏;

(网上下的php中文手册往往会不完整或者没有更新,开始就是因为我电脑上的php中文手册没有这几个参数的说明)

第二:别太相信百度、google的中文搜索结果,别人讲的不一定是对的~~

最好就是直接找最权威,最官方的说明~~

Tags: ,

1 comment
  1. 华晨 said:

    呵,没想到我不经意的一条留言让你多写了一篇文章,呵呵。
    嗯,确实,官方的在线手册是一个最好的学习资料。

Leave a Reply