Home > Database > Mysql Tutorial > php如何解决DOM乱码的问题(实例代码)

php如何解决DOM乱码的问题(实例代码)

PHPz
Release: 2018-10-18 15:19:14
Original
806 people have browsed it

最近在工作的时候遇到一个问题,在使用DOM的时候,发现了乱码的问题,后来通过查找网上的资料终于解决了,现在将解决的方法分享给大家,感兴趣的朋友们可以参考借鉴,有需要的朋友们下面来一起学习学习吧。

前言

DOM是php比较新的xml和html处理类,可以像javascript那样方便的操作DOM树,网上更多的是介绍它处理XML的情况,今天这篇文章就介绍下php解决DOM乱码的方法,下面话不多说,直接看下面的解决方法。

解决方法如下

/**
 * 请求url页面信息
 * @param str $url
 * @return str mixed|boolean
 */
function curl_get($url) {
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  //302跳转
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0');
  curl_setopt($curl, CURLOPT_REFERER, $url);
  $data = curl_exec($curl);
  $code = curl_getinfo($curl,CURLINFO_HTTP_CODE); //输出请求状态码
  curl_close($curl);
  if(200 == $code) {
    //解决乱码
    if (preg_match(&#39;#<meta[^>]*charset="?gb2312"[^>]*>#&#39;, $data)) {
      $data = iconv("gb2312","utf-8//IGNORE",$data);
      $data = preg_replace(&#39;#<meta[^>]*charset="?gb2312"[^>]*>#is&#39;, &#39;<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">&#39;, $data);
    }

    if (!preg_match(&#39;#<meta charset="utf-8"[^>]*>#is&#39;, $data)) {
      $data = str_replace(&#39;<head>&#39;, &#39;<head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">&#39;, $data);
    }

    if (preg_match(&#39;#<meta charset="utf-8"[^>]*>#is&#39;, $data)) {
      $data = preg_replace(&#39;#<meta charset="utf-8"[^>]*>#is&#39;, &#39;<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">&#39;, $data);
    }

    return $data;
  } else {
    return false;
  }

}
Copy after login

/**
 * 获取 DOMDocument 对象
 * @param str $url
 * @return boolean|DOM
 */
function getDom($url) {
  $html_content = curl_get($url);
  if(empty($html_content)) {
    //saveLog($url, &#39;请求失败&#39;);
    return false;
  }
  $dom = new DOMDocument(&#39;1.0&#39;, &#39;utf-8&#39;);
  libxml_use_internal_errors(true);
  $dom->loadHTML($html_content);
  return $dom;
}
Copy after login

$html_content = mb_convert_encoding($html_content, &#39;UTF-8&#39;, &#39;gb2312&#39;);
Copy after login

总结

【相关教程推荐】

1. php编程从入门到精通全套视频教程
2. php从入门到精通 
3. bootstrap教程

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template