我正在开发一个网络爬虫,它可以从世界各地的网站获取数据,并处理不同的语言和编码。
目前我正在使用以下函数,它在99%的情况下都有效。但是这1%让我头疼。
function convertEncoding($str) {
return iconv(mb_detect_encoding($str), "UTF-8", $str);
}
与其盲目地尝试检测编码,不如首先检查下载的页面是否有列出的字符集。字符集可以设置在HTTP响应头中,例如:
Content-Type:text/html; charset=utf-8
或者在HTML中作为元标签,例如:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
只有当两者都不可用时,才尝试使用mb_detect_encoding((或其他方法猜测编码。
不可能以100%的速率检测字符串的字符集,因为有些字符集是其他字符集的子集。如果可能,请尝试显式设置字符集,而不混合使用iconv和mbstring函数。我建议使用这样的函数,并尽可能从字符集中提供:
function convertEncoding($str, $from = 'auto', $to = "UTF-8") {
if($from == 'auto') $from = mb_detect_encoding($str);
return mb_convert_encoding ($str , $to, $from);
}
您可以尝试utf_encode($str(。
http://www.php.net/manual/en/function.utf8-encode.php#89789
或者你可以用替换内容类型的元标签
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
来自已爬网内容的标头