PHP前端开发

微信开发之如何查询精选文章代码分析

百变鹏仔 1个月前 (03-13) #前端问答
文章标签 代码

查询微信里的一些精选的,点击量比较大的文章。 
别忘记申请apikey(登录百度账号即可获取),要完成的功能是:

1、用户回复"文章",公众号要返回文章分类的编号(比如9、科技)。

2、用户回复wz9,1,腾讯     则能返回科技类文章中,关键词为“腾讯”的文章,并且显示第一页(wz9,2,腾讯则可以返回第二页,每一页返回的文章数量可以自定义,此处我放回7篇)。

详细步骤:

1、回复“文章”,返回所有文章分类的id。

if(!empty($postStr)){    //解析post来的XML为一个对象$postObj $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);  $fromUsername = $postObj-&gt;FromUserName; //请求消息的用户 $toUsername = $postObj-&gt;ToUserName; //"我"的公众号id $keyword = trim($postObj-&gt;Content); //用户发送的消息内容 $time = time(); //时间戳 $msgtype = 'text'; //消息类型:文本 $textTpl = "<xml>    <tousername></tousername>    <fromusername></fromusername>    <createtime>%s</createtime>    <msgtype></msgtype>    <content></content>    </xml>";

$which = mb_substr($keyword, 0, 2, 'UTF-8'); 

elseif($which == "文章"){    $ch = curl_init();    $url = 'http://apis.baidu.com/showapi_open_bus/weixin/weixin_article_type';    $header = array('apikey: 你自己的apikey');     // 添加apikey到header    curl_setopt($ch, CURLOPT_HTTPHEADER , $header);    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    // 执行HTTP请求    curl_setopt($ch , CURLOPT_URL , $url);    $res = curl_exec($ch);    $res = json_decode($res, true); //获取文章分类name和id     foreach($res['showapi_res_body']['typeList'] as $v){     $article[] = $v['id'] . "、" . $v['name'];    }    sort($article, SORT_NUMERIC);    foreach($article as $v){     $contentStr .= $v . "";    }    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);    echo $resultStr;    exit();    }

 2、此时echo的$resultStr就是所有文章的分类了。用户根据分类的id,可以选择自己喜欢的分类查看文章,比如回复wz19,1,篮球可以查看分类为体育的关于篮球的文章。
 具体的调用接口和实现功能的代码如下:

elseif($which == "wz"){    list($art_id, $page_id, $keyname) = split(',', $keyword);    $art_id = str_replace('wz', '', $art_id);     $ch = curl_init();    $url = 'http://apis.baidu.com/showapi_open_bus/weixin/weixin_article_list?typeId=' . $art_id . '&amp;page=' . $page_id . '&amp;key=' . urlencode($keyname);     $header = array('apikey: 你自己的apikey');     // 添加apikey到header    curl_setopt($ch, CURLOPT_HTTPHEADER , $header);    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    // 执行HTTP请求    curl_setopt($ch , CURLOPT_URL , $url);    $res = curl_exec($ch);    $res = json_decode($res, true);     foreach($res['showapi_res_body']['pagebean']['contentlist'] as $k=&gt;$v){     if($k     <title></title>    <description></description>    <picurl></picurl>    <url></url>    ";    }       $textTpl = "<xml>    <tousername></tousername>    <fromusername></fromusername>    <createtime>%s</createtime>    <msgtype></msgtype>    <articlecount>7</articlecount>    <articles>" . $items . "    </articles>    </xml> ";     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time);    echo $resultStr;    exit();     }

别忘了$header = array('apikey: ');的时候填写自己的apikey,否则接口会拒绝返回你的请求。