• TP5结合聚合数据API查询天气


    php根据城市查询天气情况
    看到有人分享java的查询全国天气情况的代码,于是我想分享一个php版本的查询天气接口。免费查询天气的接口有很多,比如百度的apistore的天气api接口,我本来想采用这个接口的,可惜今天百度apistore死活打不开了。那就用聚合数据的天气api接口吧,也是免费的,不过聚合数据的接口申请相对繁琐。

    申请地址:https://www.juhe.cn/docs/api/id/73

    1、注册一个聚合数据的账号
    2、实名认证你的账号
    3、申请你需要的api接口
    4、申请验证你的api接口
    虽然是繁琐了很多,不过返回的信息确是非常的丰富。
    好了,现在来分享一下,tp5中怎么整合进去。

    config.php中,配置你的appkey:

    //配置文件
    return [
        
        'appkey' => ''  //此处填入你的key
    ];
    

    common.php中放入请求的方法:

    <?php
    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    function juhecurl($url, $params=false, $ispost=0){
        
        $httpInfo = [];
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'JuheData' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 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;
    }
    

    控制器中,index.php的代码:

    <?php
    // +----------------------------------------------------------------------
    // | 利用聚合数据查询天气
    // +----------------------------------------------------------------------
    // | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
    // +----------------------------------------------------------------------
    // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
    // +----------------------------------------------------------------------
    // | Author: NickBai <1902822973@qq.com>
    // +----------------------------------------------------------------------
    namespace appweathercontroller;
    use thinkController;
    class Index extends Controller
    {
        public function index()
        {
            return $this->fetch();
        }
        
        /**
         * 根据城市获取天气情况
         */
        public function getWeatherByCity()
        {
            $cityName = input('param.cityname');
            $url = "http://op.juhe.cn/onebox/weather/query";
            $appkey = config('appkey');
            
            $params = [
                    "cityname" => $cityName,//要查询的城市,如:温州、上海、北京
                    "key" => $appkey,//应用APPKEY(应用详细页查询)
                    "dtype" => "",//返回数据的格式,xml或json,默认json
            ];
            $paramstring = http_build_query($params);
            
            $content = juhecurl($url, $paramstring);
            $result = json_decode($content, true);
            
            if( empty( $result ) ){
                return json( ['code' => -1, 'data' => '', 'msg' => '请求失败'] );
            }
            
            if( '0' != $result['error_code'] ){
                return json( ['code' => -2, 'data' => '', 'msg' => $result['error_code']." : ".$result['reason']] );
            }
            
            return json( ['code' => 1, 'data' => $result, 'msg' => 'success'] );
        }
    }
    

    view层中,index.html的代码如下:

    <!doctype html>
    <html>
      
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>天气查询</title>
        <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
        <script src="/static/layer/layer.js" type="text/javascript"></script>
        <link href="/static/css/style.css" rel="stylesheet" type="text/css">
      <body>
        <!--nav是导航 结束-->
        <div class="search center">
          <input class="text-pc" id="searchbox" name="" type="text" placeholder="请输入城市名称"/>
          <a class="button-pc" id="searchBtn" href="javascript:void(0);">
            <span class="icon-search"></span>
            <span class="search2 am-hide-sm-only">查询</span></a>
        </div>
        
        <div class="check-Result center" style="display:block">
            
        </div>
        
        <script type="text/javascript">
            $(function(){
                $("#searchBtn").click(function(){
                    var city = $("#searchbox").val();
                    if( '' == city ){
                        layer.alert('城市名称不能为空', { 'icon' : 2 });
                        return ;
                    }
                    var index = layer.load(0, {shade: false}); //0代表加载的风格,支持0-2
                    $.getJSON( "{:url('weather/index/getWeatherByCity')}", { 'cityname' : city }, function(res){
                        layer.close( index );
                        if( 1 == res.code ){
                            
                        }else{
                            layer.alert( res.msg , { 'icon' : 2 });
                        }
                    });
                })
            });
        </script>
        
      </body>
    </html>
    

    通过浏览器访问页面如下:


    输入你要查询的城市,比如:南京,点击查询


    json数据成功返回,这是你就可以根据你的需要渲染页面了。参数的讲解参照这里
    https://www.juhe.cn/docs/api/id/73

  • 相关阅读:
    SSM:Spring整合SpringMVC框架
    SSM:搭建整合环境
    SpringMVC:常用注解
    SpringMVC的入门案例
    base64
    windows设置exe开机自启动
    Python-wmi模块
    Base64String转为图片并保存
    java给图片添加水印图片
    uni-app中封装axios请求
  • 原文地址:https://www.cnblogs.com/annie00/p/6068523.html
Copyright © 2020-2023  润新知