PHP 获取天气

    /**
     * 获取天气
     */
    function get_tq () {

        //获取用户ip地址
        $ip = get_real_ip();
        // $ip = '123.125.71.38';
        //根据ip地址 获取用户所在城市
        $api_key = '8d6c8b8f3749aed6b1aff3aad6f40e37';           
        // 使用固定城市北京市
        $cityName = '北京市';

        //获取今天的日期
        $day = time_format(NOW_TIME, 'Y.m.d');

        if( $cityName ) {
            $tq_datas = S('site.widget.nav.tq.' . md5($cityName) . '.day.' . $day );

            if( false == $tq_datas ){
                //根据城市名 获取天气情况
                $tq_datas = @file_get_contents("http://api.map.baidu.com/telematics/v3/weather?location=" . urlencode($cityName) . "&output=json&ak=" . $api_key);
                $tq_datas = json_decode( $tq_datas, true );

                $tq_datas = $tq_datas ? $tq_datas : [];
                S('site.widget.nav.tq.' . md5($cityName) . '.day.' . $day, $tq_datas );
            }
        }

        foreach( $tq_datas['results'][0]['weather_data'] as $key=>$val ) {
            $tiqi_name = '';
            $tiqi_name = explode( '/',$val['dayPictureUrl']);
            $tiqi_name = explode( '.', end( $tiqi_name))[0];

            $tq_lists[ $key ] = $val;
            $terminal = cookie('terminal');

            if( $terminal == 'wap') {
                $tq_lists[ $key ]['ico'] = '/themes_wap/tainqi/' . $tiqi_name . ".png";
            } else {
                $tq_lists[ $key ]['ico'] = '/themes/tainqi/' . $tiqi_name . ".png";
            }
        }

        $tq_lists[0]['cityName'] = $cityName;
        if ( $terminal == 'default' ) {
            $this->tq_lists = $tq_lists;
        } else {
            $this->tq_lists = $tq_lists[0];
        }
        
        $this->ajaxReturn([ 'status' => 1 , 'name' => $tq_lists ] );
    }

 

posted @ 2019-03-19 15:18  宁佳兵  阅读(1564)  评论(0编辑  收藏  举报