本代码示例是基于PHP的聚合数据全国天气预报API服务请求的代码样例,使用前你需要:
①:通过https://www.juhe.cn/docs/api/id/39 申请一个天气预报API的appkey
样例代码包含了获取支持城市列表、根据城市获取天气预报、根据IP地址请求天气预报、根据GPS坐标请求天气、城市3小时天气预报的实现。示例代码主要是解析一些常用字段,如需要完整或其他未包含的字段,可以自行参考官方的接口,进行修改。
首先:引入封装好的天气调用类
header('Content-type:text/html;charset=utf-8'); include 'class.juhe.weather.php'; //引入天气请求类 //接口基本信息配置 $appkey = '**********'; //您申请的天气查询appkey $weather = new weather($appkey);
一、获取支持的城市列表
由于支持的城市列表基本不会这么变化,大家可以获取到列表后内置到自己的应用中,就不用每次都去请求API。
$citysResult = $weather->getCitys(); if($citysResult['error_code'] == 0){ //以下可根据实际业务需求,自行改写 ////////////////////////////////////////////////////////////////////// $citys = $citysResult['result']; foreach($citys as $ckey =>$c){ echo "ID:".$c['id'].",省份:".$c['province'].",城市:".$c['city'].",区域:".$c['district']."<br>"; } }else{ //以下可根据实际业务需求,自行改写 ////////////////////////////////////////////////////////////////////// echo $citysResult['error_code'].":".$citysResult['reason']; }
二、根据城市/ID获取天气预报
通过城市的名称或城市的ID来获取天气预报,城市id就是获取城市支持列表中返回的字段ID
$cityWeatherResult = $weather->getWeather('苏州'); if($cityWeatherResult['error_code'] == 0){ //以下可根据实际业务需求,自行改写 ////////////////////////////////////////////////////////////////////// $data = $cityWeatherResult['result']; echo "=======当前天气实况=======<br>"; echo "温度:".$data['sk']['temp']." "; echo "风向:".$data['sk']['wind_direction']." (".$data['sk']['wind_strength'].")"; echo "湿度:".$data['sk']['humidity']." "; echo "<br><br>"; echo "=======未来几天天气预报=======<br>"; foreach($data['future'] as $wkey =>$f){ echo "日期:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."<br>"; } echo "<br><br>"; echo "=======相关天气指数=======<br>"; echo "穿衣指数:".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>"; echo "紫外线强度:".$data['today']['uv_index'."<br>"; echo "舒适指数:".$data['today']['comfort_index']."<br>"; echo "洗车指数:".$data['today']['wash_index']; echo "<br><br>"; }else{ echo $cityWeatherResult['error_code'].":".$cityWeatherResult['reason']; }
三、根据用户的IP地址请求对应的天气预报
通过用户的IP地址获取用户所在地的天气预报,由于IP地址解析可能会有误差,所以有时定位到的城市不一定是用户实际的所在地。
$ipWeatherResult = $weather->getWeatherByIP('58.215.154.128'); if($ipWeatherResult['error_code'] == 0){ //以下可根据实际业务需求,自行改写 ////////////////////////////////////////////////////////////////////// $data = $ipWeatherResult['result']; echo "=======当前城市=======<br>"; echo $data['today']['city']; echo "<br><br>"; echo "=======当前天气实况=======<br>"; echo "温度:".$data['sk']['temp']." "; echo "风向:".$data['sk']['wind_direction']." (".$data['sk']['wind_strength'].")"; echo "湿度:".$data['sk']['humidity']." "; echo "<br><br>"; echo "=======未来几天天气预报=======<br>"; foreach($data['future'] as $wkey =>$f){ echo "日期:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."<br>"; } echo "<br><br>"; echo "=======相关天气指数=======<br>"; echo "穿衣指数:".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>"; echo "紫外线强度:".$data['today']['uv_index']."<br>"; echo "舒适指数:".$data['today']['comfort_index']."<br>"; echo "洗车指数:".$data['today']['wash_index']; echo "<br><br>"; }else{ echo $ipWeatherResult['error_code'].":".$ipWeatherResult['reason']; }
四、根据GPS坐标来获取对应地区的天气
无论通过二、三、四获取的天气预报,因为聚合格式都是统一的,所以解析的流程是一致的,所以没有额外的操作,只是传参上有点的差异。
$geoWeatherResult = $weather->getWeatherByGeo(116.401394,39.916042); if($geoWeatherResult['error_code'] == 0){ //以下可根据实际业务需求,自行改写 ////////////////////////////////////////////////////////////////////// $data = $geoWeatherResult['result']; echo "=======当前城市=======<br>"; echo $data['today']['city']; echo "<br><br>"; echo "=======当前天气实况=======<br>"; echo "温度:".$data['sk']['temp']." "; echo "风向:".$data['sk']['wind_direction']." (".$data['sk']['wind_strength'].")"; echo "湿度:".$data['sk']['humidity']." "; echo "<br><br>"; echo "=======未来几天天气预报=======<br>"; foreach($data['future'] as $wkey =>$f){ echo "日期:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."<br>"; } echo "<br><br>"; echo "=======相关天气指数=======<br>"; echo "穿衣指数:".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>"; echo "紫外线强度:".$data['today']['uv_index']."<br>"; echo "舒适指数:".$data['today']['comfort_index']."<br>"; echo "洗车指数:".$data['today']['wash_index']; echo "<br><br>"; }else{ echo $geoWeatherResult['error_code'].":".$geoWeatherResult['reason']; }
五、获取城市三小时预报
就是城市每3小时的天气情况
$forecastResult = $weather->getForecast("苏州"); if($forecastResult['error_code'] == 0){ //以下可根据实际业务需求,自行改写 ////////////////////////////////////////////////////////////////////// $data = $forecastResult['result']; foreach($data as $key => $d){ echo "日期:".$d['date']." (".$d['sh']."点-".$d['eh']."点) ".$d['weather']." ".$d['temp1']."~".$d["temp2"]."<br>"; } }else{ //以下可根据实际业务需求,自行改写 ////////////////////////////////////////////////////////////////////// echo $forecastResult['error_code'].":".$forecastResult['reason']; }
通过上面的示例代码,大家应该对如果调用聚合数据天气预报API有了一个大体的了解。
最后放上class.juhe.weather.php完整代码:
<!--?php // +---------------------------------------------------------------------- // | JuhePHP [ NO ZUO NO DIE ] // +---------------------------------------------------------------------- // | Copyright (c) 2010-2015 http://juhe.cn All rights reserved. // +---------------------------------------------------------------------- // | Author: Juhedata <info@juhe.cn--> // +---------------------------------------------------------------------- //---------------------------------- // 聚合数据天气预报接口请求类 //---------------------------------- class weather{ private $appkey = false; //申请的聚合天气预报APPKEY private $cityUrl = 'http://v.juhe.cn/weather/citys'; //城市列表API URL private $weatherUrl = 'http://v.juhe.cn/weather/index'; //根据城市请求天气API URL private $weatherIPUrl = 'http://v.juhe.cn/weather/ip'; //根据IP地址请求天气API URL private $weatherGeoUrl = 'http://v.juhe.cn/weather/geo'; //根据GPS坐标获取天气API URL private $forecast3hUrl = 'http://v.juhe.cn/weather/forecast3h'; //获取城市天气3小时预报API URL public function __construct($appkey){ $this->appkey = $appkey; } /** * 获取天气预报支持城市列表 * @return array */ public function getCitys(){ $params = 'key='.$this->appkey; $content = $this->juhecurl($this->cityUrl,$params); return $this->_returnArray($content); } /** * 根据城市名称/ID获取详细天气预报 * @param string $city [城市名称/ID] * @return array */ public function getWeather($city){ $paramsArray = array( 'key' => $this->appkey, 'cityname' => $city, 'format' => 2 ); $params = http_build_query($paramsArray); $content = $this->juhecurl($this->weatherUrl,$params); return $this->_returnArray($content); } /** * 根据IP地址获取当地天气预报 * @param string $ip [IP地址] * @return array */ public function getWeatherByIP($ip){ $paramsArray = array( 'key' => $this->appkey, 'ip' => $ip, 'format' => 2 ); $params = http_build_query($paramsArray); $content = $this->juhecurl($this->weatherIPUrl,$params); return $this->_returnArray($content); } /** * 根据GPS坐标获取当地的天气预报 * @param string $lon [经度] * @param string $lat [纬度] * @return array */ public function getWeatherByGeo($lon,$lat){ $paramsArray = array( 'key' => $this->appkey, 'lon' => $lon, 'lat' => $lat, 'format' => 2 ); $params = http_build_query($paramsArray); $content = $this->juhecurl($this->weatherGeoUrl,$params); return $this->_returnArray($content); } /** * 获取城市三小时预报 * @param string $city [城市名称] * @return array */ public function getForecast($city){ $paramsArray = array( 'key' => $this->appkey, 'cityname' => $city, 'format' => 2 ); $params = http_build_query($paramsArray); $content = $this->juhecurl($this->forecast3hUrl,$params); return $this->_returnArray($content); } /** * 将JSON内容转为数据,并返回 * @param string $content [内容] * @return array */ public function _returnArray($content){ return json_decode($content,true); } /** * 请求接口返回内容 * @param string $url [请求的URL地址] * @param string $params [请求的参数] * @param int $ipost [是否采用POST形式] * @return string */ public function juhecurl($url,$params=false,$ispost=0){ $httpInfo = array(); $ch = curl_init(); curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 ); curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36' ); curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 ); curl_setopt( $ch, CURLOPT_TIMEOUT , 30); curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true ); if( $ispost ) { curl_setopt( $ch , CURLOPT_POST , true ); curl_setopt( $ch , CURLOPT_POSTFIELDS , $params ); curl_setopt( $ch , CURLOPT_URL , $url ); } else { if($params){ curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params ); }else{ curl_setopt( $ch , CURLOPT_URL , $url); } } $response = curl_exec( $ch ); if ($response === FALSE) { //echo "cURL Error: " . curl_error($ch); return false; } $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE ); $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) ); curl_close( $ch ); return $response; } }