dragon071111 2017-03-13 17:37
浏览 51
已采纳

PHP DOMDocument使用HTML5 doctype正确加载HTML UTF-8编码

I am using PHP's DOMDocument class with HTML 5 document. But when I do, some utf-8 characters are "changed". I got  , ’, é etc....

Here is my code.

    $parsedUrl = 'http://www.futursparents.com/';

    $curl = curl_init();
    @curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_CONNECTTIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => TRUE,
            CURLOPT_MAXREDIRS => 5,
            CURLOPT_AUTOREFERER => FALSE,
            CURLOPT_HEADER => TRUE, // FALSE
            CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
            CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
            CURLOPT_CERTINFO => TRUE,
            CURLOPT_LOW_SPEED_LIMIT => 200,
            CURLOPT_LOW_SPEED_TIME => 50,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_PROXYTYPE => CURLPROXY_HTTP,
            CURLOPT_ENCODING => 'gzip,deflate',
            CURLOPT_URL => $parsedUrl,
        ]);
    $response = curl_exec($curl);
    $info = curl_getinfo($curl);
    $error = curl_error($curl);
    $headers = trim(substr($response, 0, curl_getinfo($curl, CURLINFO_HEADER_SIZE)));
    $content = substr($response, curl_getinfo($curl, CURLINFO_HEADER_SIZE));

    curl_close($curl);

    libxml_use_internal_errors(true);

    $domDoc = new DOMDocument();
    print_r($domDoc->encoding); // It's OK => UTF-8
    // Got   or s’ or &eacute etc....
    print_r($domDoc->saveHTML());

It seem to be an HTML5 doctype with a meta element like so <meta charset=utf-8">

If I add the charset meta tag <meta http-equiv="Content-Type" content="text/html; charset=utf-8">, It's seem to be OK.

$domDoc->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">' . $content);
// No &ensp; or s&rsquo; or &eacute etc....
print_r($domDoc->saveHTML());

Do you think this is the right solution?

  • 写回答

1条回答 默认 最新

  • douxiuyu2028 2017-03-13 18:11
    关注

    I found why.

    The DOM extension was built on libxml2 whose HTML parser was made for HTML 4. If an HTML5 doctype and a meta element like so <meta charset="utf-8"> HTML code will get interpreted as ISO-8859-something and non-ASCII chars will get converted into HTML entities.

    However the HTML4-like version will work <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    Reference: UTF-8 with PHP DOMDocument loadHTML?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里