simple_html_dom 转码 Bug 及临时修复方案
近期在使用 simple_html_dom 进行网页内容抓取。国内网站常见的字符编码包括 GBK、GB2312 和 UTF-8,其中以后两者最为普遍。
当前版本的 simple_html_dom 包含一个名为 convert_text 的方法,其实现逻辑如下。
复制代码 代码如下: // PaperG - Function to convert the text from one character set to another if the two sets are not the same. function convert_text($text) { global $debug_object; if (is_object($debug_object)) {$debug_object->debug_log_entry(1);} $converted_text = $text; $sourceCharset = ""; $targetCharset = ""; if ($this->dom) { $sourceCharset = strtoupper($this->dom->_charset); $targetCharset = strtoupper($this->dom->_target_charset); } if (is_object($debug_object)) {$debug_object->debug_log(3, "source charset: " . $sourceCharset . " target charaset: " . $targetCharset);} if (!empty($sourceCharset) && !empty($targetCharset) && (strcasecmp($sourceCharset, $targetCharset) != 0)) { // Check if the reported encoding could have been incorrect and the text is actually already UTF-8 if ((strcasecmp($targetCharset, 'UTF-8') == 0) && ($this->is_utf8($text))) { $converted_text = $text; } else { $converted_text = iconv($sourceCharset, $targetCharset, $text); } } // Lets make sure that we don't have that silly BOM issue with any of the utf-8 text we output. if ($targetCharset == 'UTF-8') { if (substr($converted_text, 0, 3) == "\xef\xbb\xbf") { $converted_text = substr($converted_text, 3); } if (substr($converted_text, -3) == "\xef\xbb\xbf") { $converted_text = substr($converted_text, 0, -3); } } return $converted_text; }
重点关注以下这一行代码:
复制代码 代码如下: $converted_text = iconv($sourceCharset, $targetCharset, $text);
这行代码会导致转码结果不正确。例如,当源编码为 GB2312 时,转换后的文本会出现乱码。
复制代码 代码如下: 4月26日在鏈濋槼公园马术场举行的2014浪琴国际马联场地障碍世界杯中国联赛资格赛上,24岁的韩壮壮不仅拿到零罚分的成绩 ...第7个出场的鍖椾含奥运骑手赵志文第一个收获零罚分,用时77秒07 ...
这证实了该库内部的转码功能存在缺陷。鉴于我使用 simple_html_dom 的主要目的是构建 DOM 树,并未打算深入修复此 Bug,因此采取了简单的绕过策略。
复制代码 代码如下: $converted_text = iconv($sourceCharset, $targetCharset, $text);
将其修改为:
复制代码 代码如下: $converted_text = $text;
即取消转码步骤,直接使用原始文本。这样便解决了问题,可以继续后续工作。