這是來自百度API的一個天氣查詢的接口,支持歷史7天和未來4天的天氣情況查詢,接口不錯,分享給大家。
接口申請地址:http://apistore.baidu.com/apiworks/servicedetail/112.html
首先,獲取一下apikey(貌似需要手機驗證碼認證下)
我調用的是歷史7天和未來4天的接口,接口地址是:
http://apis.baidu.com/apistore/weatherservice/recentweathers
我將這個天氣查詢的功能集成在了微信公眾平台上,支持未來4天天氣查詢,包括:當前溫度、pm值、風向、風力、最高溫度、最低溫度、天氣狀態的查詢,效果如下:
閒話不多說,我就喜歡來點直接的,核心代碼如下:
1 //接收到文本信息 2 private function receiveText($object){ 3 //多個空格縮為一個 4 $keyword = $object->Content; 5 $keyword=preg_replace("/\s(?=\s)/","\\1",$keyword); 6 $funcFlag = 0; 7 if(strpos($keyword," ")){ 8 //echo '有空格'; 9 $arr = explode(" ",$keyword); 10 if($arr[0]=="天氣"){ 11 $dateArray = array(); 12 $ch = curl_init(); 13 $city=urlencode($arr[1]); 14 $url = 'http://apis.baidu.com/apistore/weatherservice/recentweathers?cityname='.$city; 15 $header = array( 16 'apikey: 6512ad3a465e3a9e3d0d1da56639626c', 17 ); 18 curl_setopt($ch, CURLOPT_HTTPHEADER , $header); 19 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 20 curl_setopt($ch , CURLOPT_URL , $url); 21 $res = curl_exec($ch); 22 $data = json_decode($res,true); 23 $cityname=$data['retData']['city']; 24 $citydate=$data['retData']['today']['date']; 25 $cityweek=$data['retData']['today']['week']; 26 $citytemp=$data['retData']['today']['curTemp']; 27 $citypm=$data['retData']['today']['aqi']; 28 $cityhightemp=$data['retData']['today']['hightemp']; 29 $citylowtemp=$data['retData']['today']['lowtemp']; 30 $citytype=$data['retData']['today']['type']; 31 $cityfengli=$data['retData']['today']['fengli']; 32 $cityfengxiang=$data['retData']['today']['fengxiang']; 33 $cityforecast=$data['retData']['forecast']; 34 35 $out="今日溫度:".$citylowtemp."~".$cityhightemp."\n\r"."當前溫度:".$citytemp."\n\r"."天氣情況:".$citytype."\n\r"."PM2.5值:".$citypm."\n\r風向風力:".$cityfengxiang." ".$cityfengli; 36 $dateArray[] = array("Title"=>$cityname."\n\r".$citydate." ".$cityweek,"Description"=>"","Picurl"=>"","Url" =>""); 37 $dateArray[] = array("Title"=>$out,"Description"=>"","Picurl"=>"","Url" =>""); 38 for($i=0;$i<count($cityforecast);$i++){ 39 $outstr="☀ ".$cityforecast[$i]["date"]." ".$cityforecast[$i]["week"]."\n\r氣溫:".$cityforecast[$i]["lowtemp"]."~".$cityforecast[$i]["hightemp"]."\n\r風力:".$cityforecast[$i]["fengxiang"]." ".$cityforecast[$i]["fengli"]."\n\r天氣:".$cityforecast[$i]["type"]; 40 $dateArray[] = array("Title"=>$outstr,"Description"=>"","Picurl"=>"","Url" =>""); 41 } 42 $resultStr = $this->transmitNews($object, $dateArray, $funcFlag); 43 } 44 }else{ 45 //echo '沒有空格'; 46 if($keyword=="天氣"){ 47 $dateArray = array(); 48 $dateArray[] = array("Title"=>"查詢格式錯誤","Description"=>"","Picurl"=>"","Url" =>""); 49 $dateArray[] = array("Title"=>"正確格式例:天氣 北京","Description"=>"","Picurl"=>"","Url" =>""); 50 $resultStr = $this->transmitNews($object, $dateArray, $funcFlag); 51 } 52 } 53 return $resultStr; 54 }
查詢格式:“天氣 城市名”