您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php解决DOM乱码的方法

2025/12/29 20:25:16发布26次查看
最近在工作的时候遇到一个问题,在使用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('#<meta[^>]*charset="?gb2312"[^>]*>#', $data)) { $data = iconv("gb2312","utf-8//ignore",$data); $data = preg_replace('#<meta[^>]*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><meta 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', '<meta http-equiv="content-type" content="text/html;charset=utf-8">', $data); } return $data; } else { return false; } }
/** * 获取 domdocument 对象 * @param str $url * @return boolean|dom */ function getdom($url) { $html_content = curl_get($url); if(empty($html_content)) { //savelog($url, '请求失败'); return false; } $dom = new domdocument('1.0', 'utf-8'); libxml_use_internal_errors(true); $dom->loadhtml($html_content); return $dom; }
$html_content = mb_convert_encoding($html_content, 'utf-8', 'gb2312');
以上就是本文的全部内容,希望对大家的学习有所帮助。
相关推荐:
php实现头像上传预览实例详解
php头像上传预览实例详解
php 序列化和反序列化函数图文详解
以上就是php解决dom乱码的方法的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product