相關(guān)關(guān)鍵詞
關(guān)于我們
最新文章
PHP調(diào)用API接口實現(xiàn)天氣查詢功能的示例

天氣預(yù)報查詢接口API,在這里我使用的是國家氣象局天氣預(yù)報接口
使用較多的還有:新浪天氣預(yù)報接口、百度天氣預(yù)報接口、google天氣接口、Yahoo天氣接口等等。
1、查詢方式
根據(jù)地名查詢各城市天氣情況
2.請求URL地址
http://route.showapi.com/9-2
3、接口參數(shù)說明:
一、系統(tǒng)級參數(shù)(所有接入點都需要的參數(shù)):
二、應(yīng)用級參數(shù)(每個接入點有自己的參數(shù)):
4.返回參數(shù)
以JSON格式返回結(jié)果
1)系統(tǒng)級參數(shù)(所有接入點都會返回的參數(shù))
2)應(yīng)用級參數(shù)(系統(tǒng)級輸出參數(shù)showapi_res_body字段中的json數(shù)據(jù)結(jié)構(gòu))
具體調(diào)用操作:
PHP中自帶了處理json格式字符串的內(nèi)置函數(shù),下面做一個事例,并給出完整代碼:
<?php //查找淄博天氣情況 //接口自帶編寫的數(shù)組 $showapi_appid = '46435'; //替換此值,在官網(wǎng)的"我的應(yīng)用"中找到相關(guān)值 $showapi_secret = '7c55aef4ede442ffa49b24c2c808e523'; //替換此值,在官網(wǎng)的"我的應(yīng)用"中找到相關(guān)值 $paramArr = array( 'showapi_appid'=> $showapi_appid, 'areaid'=> "", 'area'=> "淄博", 'needMoreDay'=> "", 'needIndex'=> "", 'needHourData'=> "", 'need3HourForcast'=> "", 'needAlarm'=> "" //添加其他參數(shù) ); //創(chuàng)建參數(shù)(包括簽名的處理)接口自帶編寫的數(shù)組 function createParam ($paramArr,$showapi_secret) { $paraStr = ""; $signStr = ""; ksort($paramArr); foreach ($paramArr as $key => $val) { if ($key != '' && $val != '') { $signStr .= $key.$val; $paraStr .= $key.'='.urlencode($val).'&'; } } $signStr .= $showapi_secret;//排好序的參數(shù)加上secret,進(jìn)行md5 $sign = strtolower(md5($signStr)); $paraStr .= 'showapi_sign='.$sign;//將md5后的值作為參數(shù),便于服務(wù)器的效驗 return $paraStr; } $param = createParam($paramArr,$showapi_secret); $url = 'http://route.showapi.com/9-2?'.$param; //獲取json格式的數(shù)據(jù) $result = file_get_contents($url); //對json格式的字符串進(jìn)行編碼 $arr = (json_decode($result)); $v = $arr->showapi_res_body;$attr = $v->f1; //所需要的數(shù)據(jù)進(jìn)行調(diào)用 $arr1 = $attr->day_weather; $arr2 = $attr->night_weather; $arr3 = $attr->night_air_temperature; $arr4 = $attr->day_air_temperature; $arr5 = $attr->day_wind_direction; $arr6 = $attr->night_weather_pic; echo $arr6; ?> //將所需要的數(shù)據(jù)添加到數(shù)據(jù)庫 <?php require_once "./DBDA.class.php"; $db = new DBDA(); $sql = "insert into weather values('','{$arr1}','{$arr2}')"; $arr = $db->query($sql); ?>