相關(guān)關(guān)鍵詞
關(guān)于我們
最新文章
- PHP中opcode緩存簡單用法分析
- thinkPHP控制器變量在模板中的顯示方法示例
- PHP move_uploaded_file() 函數(shù)(將上傳的文件移動(dòng)到新位置)
- dirname(__FILE__)的含義和應(yīng)用說明
- thinkPHP5框架實(shí)現(xiàn)分頁查詢功能的方法示例
- PHP中單雙號(hào)與變量
- PHP獲得當(dāng)日零點(diǎn)時(shí)間戳的方法分析
- Laravel ORM對(duì)Model::find方法進(jìn)行緩存示例詳解
- PHP讀寫文件高并發(fā)處理操作實(shí)例詳解
- 【CLI】利用Curl下載文件實(shí)時(shí)進(jìn)度條顯示的實(shí)現(xiàn)
PHP調(diào)用API接口實(shí)現(xiàn)天氣查詢功能的示例

天氣預(yù)報(bào)查詢接口API,在這里我使用的是國家氣象局天氣預(yù)報(bào)接口
使用較多的還有:新浪天氣預(yù)報(bào)接口、百度天氣預(yù)報(bào)接口、google天氣接口、Yahoo天氣接口等等。
1、查詢方式
根據(jù)地名查詢各城市天氣情況
2.請(qǐng)求URL地址
http://route.showapi.com/9-2
3、接口參數(shù)說明:
一、系統(tǒng)級(jí)參數(shù)(所有接入點(diǎn)都需要的參數(shù)):
二、應(yīng)用級(jí)參數(shù)(每個(gè)接入點(diǎn)有自己的參數(shù)):
4.返回參數(shù)
以JSON格式返回結(jié)果
1)系統(tǒng)級(jí)參數(shù)(所有接入點(diǎn)都會(huì)返回的參數(shù))
2)應(yīng)用級(jí)參數(shù)(系統(tǒng)級(jí)輸出參數(shù)showapi_res_body字段中的json數(shù)據(jù)結(jié)構(gòu))
具體調(diào)用操作:
PHP中自帶了處理json格式字符串的內(nèi)置函數(shù),下面做一個(gè)事例,并給出完整代碼:
<?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ù)器的效驗(yàn) return $paraStr; } $param = createParam($paramArr,$showapi_secret); $url = 'http://route.showapi.com/9-2?'.$param; //獲取json格式的數(shù)據(jù) $result = file_get_contents($url); //對(duì)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); ?>