全國天氣預報數據API調用PHP示例


本代碼示例是基於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;  
    }  
  
}  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM