首页 > WEB开发 > 代码 > PHP通过气象局开放API查询指定城市(区县)天气
2015
02-02

PHP通过气象局开放API查询指定城市(区县)天气

具体应用说不上,写这个功能纯粹为了好玩,可能在网站的小挂件里没准能用上这样的功能,或者一些生活类网站比较适用,在正式进入本话题之前,必须要通过PHP将JSON格式省市(区)二级数据插入数据库,才能进行接下来的天气查询操作,所谓巧妇难为无米之炊,斯理也。在完成省市信息入库之后,理一下实现思路:前台通过搜索框执行ajax请求,后台根据城市名称查询城市编码,然后通过城市编码组装成API接口获取该城市天气信息,返回到前台,其实还是很简单的,代码如下:

1.前台代码 weather.php:

<?php
/*
 * author:phpxs.com
 * website:
 * url:http://www.phpxs.com/post/2945
 */
?>

<script type="text/javascript"
src="/uploads/201502/02/14228784541.js">
</script>

<input type="text" id="city_name" name="city"/>
<button id="query" 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.后台代码 getweather.php:

<?php

/*
* author:phpxs.com
* website:
* url:http://www.phpxs.com/post/2945
*/

if (isset($_POST['city'])) {
    $city = $_POST['city'];
    //通过城市名称获取城市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();
    //通过城市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格式结果
    echo $ret;
}else{
    echo '请输入要查询的城市名!';
}
?>

 3.效果演示:

weather

编程技巧