【问题标题】:Simple HTML DOM For Parsing generates Error用于解析的简单 HTML DOM 生成错误
【发布时间】:2013-08-12 09:07:59
【问题描述】:

我正在使用简单的 HTML DOM 类进行网页抓取。问题是它会针对 unicode 字符生成奇怪的字符。

हंगामा है कà¥à¤¯à¥‚ठबरपा / अकबर इलाहाबादी 

针对印地语 unicode 字符。

लेकिन इतना तो हुआ कुछ लोग

这是我的印地语文本。

当我打印屏幕输出时,它以相同的奇怪字符输出。

function getDomContent($data) {
    $html = new simple_html_dom();
    $html->load($data);

    foreach ($html->find('table[id=content] li') as $element) {
        $content[] = $element->plaintext;
    }

    return $content;
}

我的卷曲功能

function getContent($url) {
    $timeout = 5;
    $ch = curl_init();
    $user_agent = 'Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
    curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$data = getContent($url);
$content = getDomContent($data);
echo '<pre>Array Content: ' . '<br/>';
print_r($content);
die($query);

【问题讨论】:

    标签: php curl html-parsing


    【解决方案1】:

    编码似乎有问题。 尝试使用iconv PHP 函数。

    $text = iconv("current text codification", "UTF-8", $text)
    

    但如果您不知道当前编码,请尝试将其设置为使用 iconv_set_encoding 的全局配置。

    iconv_set_encoding("internal_encoding", "UTF-8");
    

    【讨论】:

    • 具体在哪里做??在我的所有函数之前或在函数中或在 curl 或其他地方。
    • 如果你知道你当前的编码,你必须在接收文本后使用第一个函数,但如果你想使用全局配置,只需在调用你的函数之前使用第二个函数 getContent跨度>
    • 第二个函数什么也没做...第一个函数跳过我返回空字符串的内容。如果我使用它。
    • 使用 curl 获取 html 或使用 getDomContent 解析 html 时出现奇怪字符的地方?
    • 当我得到内容时getContent函数。
    【解决方案2】:

    我通过在页面中添加标题来解决它...

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

    它解决了所有问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 2018-02-23
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多