您的位置:首页 > 产品设计 > UI/UE

使用QueryList解析微信文章

2017-02-27 20:56 459 查看
背景:最近工作中需要做一个通过微信文章url抓取微信文章的功能,网页解析使用的是QueryList。将代码实现的逻辑记录一下。

具体实现代码如下:

/**
* @param $url  微信文章url
* @return bool
*/
function spideWx($url){
if(empty($url)) return false;
$_host = parse_url($url, PHP_URL_HOST);  //获取主机名
if($_host !== 'mp.weixin.qq.com') return false;  //不是来自微信文章

$html = file_get_contents($url);
if(empty($html)) return false;
$html = str_replace("<!--headTrap<body></body><head></head><html></html>-->", "", $html);  //去除微信干扰元素!!!否则乱码
preg_match("/var msg_cdn_url = \".*\"/", $html, $matches);   //获取微信封面图
$coverImgUrl = $matches[0];
$coverImgUrl = substr(explode('var msg_cdn_url = "', $coverImgUrl)[1], 0, -1);
$rules = array(   //设置QueryList的解析规则
'content' => array('#js_content', 'html'),  //文章内容
'title' => array('#activity-name', 'text'),  //文章标题
'author'=> array('.rich_media_meta_text:eq(1)','text'),  //作者
'account_name' => array('#js_profile_qrcode .profile_nickname','text'),  //公众号
'account_en_name' => array('#js_profile_qrcode .profile_meta:eq(0) .profile_meta_value','text'),  //公众号英文标识
);
//替换图片链接,解决微信图片防盗链
$_link = 'http://read.html5.qq.com/image?src=forum&q=5&r=0&imgflag=7&imageUrl=';
$data = QueryList::Query($html,$rules)->getData();   //执行解析
$_res = $data[0];  //获取解析结果
if(empty($_res)) return false;  //解析失败
$_res['thumb'] = $_link.$coverImgUrl;   //封面图
$_res['title_crc'] = sprintf("%u", crc32($_res['title']));   //标题crc
$_res['url_crc'] = sprintf("%u", crc32($url));   //url-crc
$pattern = '/<img([^>]*)data-src\s*=\s*([\' "])([\s\S]*?)([^>]*)/';    //正则替换内容中的图片链接
$_res['content'] = preg_replace($pattern, '<img$1src=$2'.$_link.'$3$4', $_res['content']);

return $_res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  微信 php