前言
DOM是PHP比较新的xml和html处理类,可以像javascript那样方便的操作DOM树,网上更多的是介绍它处理XML的情况,今天这篇文章就介绍下PHP解决DOM乱码的方法,下面话不多说,直接看下面的解决方法。
解决方法如下
PHP;">
/**
* 请求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('#]*charset="?gb2312"[^>]*>#',$data)) {
$data = iconv("gb2312","utf-8//IGNORE",$data);
$data = preg_replace('#]*charset="?gb2312"[^>]*>#is','<Meta http-equiv="Content-Type" content="text/html;charset=UTF-8">',$data);
}
if (!preg_match('#<meta charset="utf-8"[^>]*>#is',$data)) {
$data = str_replace('<head>','<head><<a href="https://www.jb51.cc/tag/Meta/" target="_blank" class="keywords">Meta</a> http-equiv="Content-Type" content="text/html;charset=UTF-8">',$data);
}
if (preg_match('#<meta charset="utf-8"[^>]*>#is',$data)) {
$data = preg_replace('#<meta charset="utf-8"[^>]*>#is',$data);
}
return $data;
} else {
return false;
}
}
loadHTML($html_content);
return $dom;
}
PHP;">
$html_content = mb_convert_encoding($html_content,'UTF-8','gb2312');