本文實例講述了PHP調(diào)用全國天氣預報數(shù)據(jù)接口查詢天氣。分享給大家供大家參考,具體如下:
基于PHP的聚合數(shù)據(jù)全國天氣預報API服務請求的代碼樣例
本代碼示例是基于PHP的聚合數(shù)據(jù)全國天氣預報API服務請求的代碼樣例,使用前你需要:
①:通過https://www.juhe.cn/docs/api/id/39 申請一個天氣預報API的appkey
樣例代碼包含了獲取支持城市列表、根據(jù)城市獲取天氣預報、根據(jù)IP地址請求天氣預報、根據(jù)GPS坐標請求天氣、城市3小時天氣預報的實現(xiàn)。示例代碼主要是解析一些常用字段,如需要完整或其他未包含的字段,可以自行參考官方的接口,進行修改。
首先:引入封裝好的天氣調(diào)用類
header('Content-type:text/html;charset=utf-8');
include 'class.juhe.weather.php'; //引入天氣請求類
//接口基本信息配置
$appkey = '**********'; //您申請的天氣查詢appkey
$weather = new weather($appkey);
一、獲取支持的城市列表
由于支持的城市列表基本不會這么變化,大家可以獲取到列表后內(nèi)置到自己的應用中,就不用每次都去請求API。
$citysResult = $weather->getCitys();
if($citysResult['error_code'] == 0){ //以下可根據(jù)實際業(yè)務需求,自行改寫
//////////////////////////////////////////////////////////////////////
$citys = $citysResult['result'];
foreach($citys as $ckey =>$c){
echo "ID:".$c['id'].",省份:".$c['province'].",城市:".$c['city'].",區(qū)域:".$c['district']."br>";
}
}else{ //以下可根據(jù)實際業(yè)務需求,自行改寫
//////////////////////////////////////////////////////////////////////
echo $citysResult['error_code'].":".$citysResult['reason'];
}
二、根據(jù)城市/ID獲取天氣預報
通過城市的名稱或城市的ID來獲取天氣預報,城市id就是獲取城市支持列表中返回的字段ID
$cityWeatherResult = $weather->getWeather('蘇州');
if($cityWeatherResult['error_code'] == 0){ //以下可根據(jù)實際業(yè)務需求,自行改寫
//////////////////////////////////////////////////////////////////////
$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 "=======相關天氣指數(shù)=======br>";
echo "穿衣指數(shù):".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."br>";
echo "紫外線強度:".$data['today']['uv_index']."br>";
echo "舒適指數(shù):".$data['today']['comfort_index']."br>";
echo "洗車指數(shù):".$data['today']['wash_index'];
echo "br>br>";
}else{
echo $cityWeatherRe
}
三、根據(jù)用戶的IP地址請求對應的天氣預報
通過用戶的IP地址獲取用戶所在地的天氣預報,由于IP地址解析可能會有誤差,所以有時定位到的城市不一定是用戶實際的所在地。
$ipWeatherResult = $weather->getWeatherByIP('58.215.154.128');
if($ipWeatherResult['error_code'] == 0){ //以下可根據(jù)實際業(yè)務需求,自行改寫
//////////////////////////////////////////////////////////////////////
$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 "=======相關天氣指數(shù)=======br>";
echo "穿衣指數(shù):".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."br>";
echo "紫外線強度:".$data['today']['uv_index']."br>";
echo "舒適指數(shù):".$data['today']['comfort_index']."br>";
echo "洗車指數(shù):".$data['today']['wash_index'];
echo "br>br>";
}else{
echo $ipWeatherResult['error_code'].":".$ipWeatherResult['reason'];
}
四、根據(jù)GPS坐標來獲取對應地區(qū)的天氣
無論通過二、三、四獲取的天氣預報,因為聚合格式都是統(tǒng)一的,所以解析的流程是一致的,所以沒有額外的操作,只是傳參上有點的差異。
$geoWeatherResult = $weather->getWeatherByGeo(116.401394,39.916042);
if($geoWeatherResult['error_code'] == 0){ //以下可根據(jù)實際業(yè)務需求,自行改寫
//////////////////////////////////////////////////////////////////////
$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 "=======相關天氣指數(shù)=======br>";
echo "穿衣指數(shù):".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."br>";
echo "紫外線強度:".$data['today']['uv_index']."br>";
echo "舒適指數(shù):".$data['today']['comfort_index']."br>";
echo "洗車指數(shù):".$data['today']['wash_index'];
echo "br>br>";
}else{
echo $geoWeatherResult['error_code'].":".$geoWeatherResult['reason'];
}
五、獲取城市三小時預報
就是城市每3小時的天氣情況
$forecastResult = $weather->getForecast("蘇州");
if($forecastResult['error_code'] == 0){ //以下可根據(jù)實際業(yè)務需求,自行改寫
//////////////////////////////////////////////////////////////////////
$data = $forecastResult['result'];
foreach($data as $key => $d){
echo "日期:".$d['date']." (".$d['sh']."點-".$d['eh']."點) ".$d['weather']." ".$d['temp1']."~".$d["temp2"]."br>";
}
}else{ //以下可根據(jù)實際業(yè)務需求,自行改寫
//////////////////////////////////////////////////////////////////////
echo $forecastResult['error_code'].":".$forecastResult['reason'];
}
通過上面的示例代碼,大家應該對如果調(diào)用聚合數(shù)據(jù)天氣預報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-->
// +----------------------------------------------------------------------
//----------------------------------
// 聚合數(shù)據(jù)天氣預報接口請求類
//----------------------------------
class weather{
private $appkey = false; //申請的聚合天氣預報APPKEY
private $cityUrl = 'http://v.juhe.cn/weather/citys'; //城市列表API URL
private $weatherUrl = 'http://v.juhe.cn/weather/index'; //根據(jù)城市請求天氣API URL
private $weatherIPUrl = 'http://v.juhe.cn/weather/ip'; //根據(jù)IP地址請求天氣API URL
private $weatherGeoUrl = 'http://v.juhe.cn/weather/geo'; //根據(jù)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);
}
/**
* 根據(jù)城市名稱/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);
}
/**
* 根據(jù)IP地址獲取當?shù)靥鞖忸A報
* @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);
}
/**
* 根據(jù)GPS坐標獲取當?shù)氐奶鞖忸A報
* @param string $lon [經(jīng)度]
* @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內(nèi)容轉為數(shù)據(jù),并返回
* @param string $content [內(nèi)容]
* @return array
*/
public function _returnArray($content){
return json_decode($content,true);
}
/**
* 請求接口返回內(nèi)容
* @param string $url [請求的URL地址]
* @param string $params [請求的參數(shù)]
* @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;
}
}
更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《php curl用法總結》、《PHP網(wǎng)絡編程技巧總結》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結》、《PHP數(shù)據(jù)結構與算法教程》及《PHP中json格式數(shù)據(jù)操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
您可能感興趣的文章:- PHP封裝XML和JSON格式數(shù)據(jù)接口操作示例
- php的api數(shù)據(jù)接口書寫實例(推薦)
- PHP實現(xiàn)chrome表單請求數(shù)據(jù)轉換為接口使用的json數(shù)據(jù)
- PHP實現(xiàn)騰訊短網(wǎng)址生成api接口實例
- PHP接入支付寶接口失效流程詳解
- PHP語言對接抖音快手小紅書視頻/圖片去水印API接口源碼
- PHP預定義接口——Iterator用法示例
- php與阿里云短信接口接入操作案例分析
- PHP開發(fā)API接口簽名生成及驗證操作示例
- PHP接口類(interface)的定義、特點和應用示例
- 微信小程序開發(fā)之獲取用戶手機號碼(php接口解密)
- PHP 對象接口簡單實現(xiàn)方法示例
- PHP開發(fā)api接口安全驗證操作實例詳解
- 如何用PHP編寫簡單的api數(shù)據(jù)接口