标签:
这是来自百度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 }
查询格式:“天气 城市名”
标签:
原文地址:http://www.cnblogs.com/lcl666518/p/5387956.html