2011-06-25 61 views
1

我想用cURL在PHP中编写我自己的网络爬虫。在PHP中猜测字符集编码

[...] 
mb_internal_encoding('UTF-8'); 
mb_language('uni'); 
$this->_curl = curl_init(); 
curl_setopt($this->_curl, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($this->_curl, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($this->_curl, CURLOPT_FOLLOWLOCATION, false); 
curl_setopt($this->_curl, CURLOPT_MAXREDIRS, 0); 
curl_setopt($this->_curl, CURLOPT_TIMEOUT, 10); 
curl_setopt($this->_curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10'); 
curl_setopt($this->_curl, CURLOPT_HEADER, true); 
curl_setopt($this->_curl, CURLOPT_RETURNTRANSFER, true); 
$header = array(
      "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 
      "Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3", 
      "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7", 
      "Keep-Alive: 115", 
      "Connection: keep-alive", 
); 
curl_setopt($this->_curl, CURLOPT_HTTPHEADER, $header); 
curl_setopt($this->_curl, CURLOPT_URL, $url); 
curl_setopt($this->_curl, CURLOPT_POST, false); 
curl_setopt($this->_curl, CURLOPT_POSTFIELDS, array()); 
curl_setopt($this->_curl, CURLOPT_HTTPGET, true); 
$page = curl_exec($this->_curl); 
[...] 

问题是网站的字符集。正如你可以在

http://blog.163.com/drewes_4711/blog/static/179317021201151624826557/

看到有一个头"Content-Type: ...;charset=GBK"所以我可以做mb_convert_encoding($content, "UTF-8", "GBK");但我应该怎么做

http://tech.hexun.com/2011-06-21/130756909.html

似乎是相同的字符集,但它不在HTTP标头中给出。所以我有德语变音符号,中文和亚洲语言的巨大问题...有没有任何模块或片段,我可以使用cURL来确定任何下载的HTML网站的字符集?

回答

2

这第二个链接包含:看起来像普通的ASCII

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 

所有数据之前。所以你可以尝试一下,如果HTTP头没有提供线索,只是解析(假设纯ASCII,而不是UTF-8 - 这可能会中断),直到找到该头。

这显然不能保证工作。如果服务器没有发送编码,并且页面也没有该标题,那么你运气不好。没有通用的手段来检测给定数据的编码。

+0

@ mu,@ Mat:太好了。我不知道,为什么我没有自己寻找这个。但是当我发送''Accept-Charset:utf-8“'时,假设内容是UTF-8并不正确,我在头文件或内容中找不到任何内容类型? – rabudde

+0

在理想的世界里,你确实不会有这个问题。但是,如果您的应用程序只能满足配置良好,符合标准的网络服务器和网页......那么您将缺少很多东西:-) – Mat

+0

当然。我现在要尝试解析字符集定义的头文件和内容,之后我将使用'mb_check_encoding($ string,'UTF-8')'检查,否则,我将执行'utf8_encode($ string)'' – rabudde