今天,有个需求是要抓取网页内容,结果遇到了中文乱码的问题。下面,是我处理测试的通过。
一、iconv("gb2312", "UTF-8",'测试')php
$getcontent = iconv("gb2312", "UTF-8",'测试'); print_r($getcontent);
报错:iconv(): Detected an illegal character in input string
缘由:考虑到GB2312字符集比较小
解决办法:将GB2312字符集改为GBK。html
二、iconv("GBK", "UTF-8",'测试')函数
$getcontent = iconv("GBK", "UTF-8",'测试'); print_r($getcontent);
报错:乱码状态
解决办法:通常状况下用 iconv,只有当遇到没法肯定原编码是何种编码,或者iconv转化后没法正常显示时才用mb_convert_encoding 函数测试
三、mb_convert_encoding($contents, "UTF-8","auto")编码
$getcontent = mb_convert_encoding($contents, "UTF-8","auto"); print_r($getcontent);
成功了!有错误的地方或者更好的办法,但愿能够多多指教(*^▽^*)code
Tip:mb_convert_encoding的使用方法
参考网址:http://www.php.cn/manual/view/5241.htmlhtm
string mb_convert_encoding ( string $str , string $to_encoding [, mixed $from_encoding = mb_internal_encoding() ] )
说明:将 string 类型 str 的字符编码从可选的 from_encoding 转换到 to_encoding。ip
str:要编码的 string 。
to_encoding:str 要转换成的编码类型。
from_encoding:在转换前经过字符代码名称来指定。它能够是一个 array 也能够是逗号分隔的枚举列表。 若是没有提供 from_encoding,则会使用内部(internal)编码。get