PHP通過(guò)氣象局開(kāi)放API查詢指定城市(區(qū)縣)天氣
具體應(yīng)用說(shuō)不上,寫這個(gè)功能純粹為了好玩,可能在網(wǎng)站的小掛件里沒(méi)準(zhǔn)能用上這樣的功能,或者一些生活類網(wǎng)站比較適用,在正式進(jìn)入本話題之前,必須要通過(guò)PHP將JSON格式省市(區(qū))二級(jí)數(shù)據(jù)插入數(shù)據(jù)庫(kù),才能進(jìn)行接下來(lái)的天氣查詢操作,所謂巧婦難為無(wú)米之炊,斯理也。在完成省市信息入庫(kù)之后,理一下實(shí)現(xiàn)思路:前臺(tái)通過(guò)搜索框執(zhí)行ajax請(qǐng)求,后臺(tái)根據(jù)城市名稱查詢城市編碼,然后通過(guò)城市編碼組裝成API接口獲取該城市天氣信息,返回到前臺(tái),其實(shí)還是很簡(jiǎn)單的,代碼如下:
1.前臺(tái)代碼 weather.php:
<?php/* * author:phpxs.com * website: * url:http://www.phpxs.com/post/2945 */?><script type='text/javascript'src='http://m.cgvv.com.cn/uploads/201502/02/14228784541.js'></script><input type='text' name='city'/><button onclick='queryWeather();'>查詢</button><div id='show'></div><script type='text/javascript'> function queryWeather(){$.post(’getweather.php’, {city: $('#city_name').val()}, function(data) { //optional stuff to do after success var weather = data.weatherinfo.weather1; var temp = data.weatherinfo.temp1; $('#show').html(weather+','+temp); },’json’); }</script>
2.后臺(tái)代碼 getweather.php:
<?php/** author:phpxs.com* website:* url:http://www.phpxs.com/post/2945*/if (isset($_POST[’city’])) { $city = $_POST[’city’]; //通過(guò)城市名稱獲取城市ID $pdo = new PDO(’mysql:host=localhost;dbname=test;charset=utf8’,’root’,’root’); $stmt = $pdo->prepare(’SELECT id FROM city WHERE name=:name’); $stmt->bindParam(’:name’,$city); $stmt->execute(); $cid = $stmt->fetchColumn(); //通過(guò)城市ID獲取城市天氣詳情 $api = 'http://m.weather.com.cn/data/'.$cid.'.html'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, ’Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.1 Safari/537.11’); $ret = curl_exec($ch); curl_close($ch); //返回獲取json格式結(jié)果 echo $ret;}else{ echo ’請(qǐng)輸入要查詢的城市名!’;}?>
3.效果演示:
相關(guān)文章:
1. WMLScript腳本程序設(shè)計(jì)第1/9頁(yè)2. 利用CSS3新特性創(chuàng)建透明邊框三角3. XML入門的常見(jiàn)問(wèn)題(三)4. Vue3獲取DOM節(jié)點(diǎn)的3種方式實(shí)例5. 多級(jí)聯(lián)動(dòng)下拉選擇框,動(dòng)態(tài)獲取下一級(jí)6. 不要在HTML中濫用div7. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)8. vue實(shí)現(xiàn)將自己網(wǎng)站(h5鏈接)分享到微信中形成小卡片的超詳細(xì)教程9. 前端html+css實(shí)現(xiàn)動(dòng)態(tài)生日快樂(lè)代碼10. 詳解CSS偽元素的妙用單標(biāo)簽之美
