美文网首页
新浪天气API接口获取最近几天天气数据!

新浪天气API接口获取最近几天天气数据!

作者: DragonersLi | 来源:发表于2017-08-04 15:52 被阅读109次

    新浪天气api接口文件:Weather.class.php

    <?php
    /*
     * 获取连续几天天气
     */
    class Weather
    {
    
        //日期数组,0代表几天
        private $_day;
        
        public function __construct($day = 0){
         
            $this->_day = range(0,(int)$day);
     
        }
        //获取xml信息
        public function getXmlInfo($city_name)
        {
            //城市名称
            $city = $this->filter($city_name);
    
            $return = array();
            //具体日期
            foreach ($this->_day as $item)
            {
                //新浪天气api
    
                $api_address = "http://php.weather.sina.com.cn/xml.php?city={$city}&password=DJOYnieT8234jlsK&day={$item}";
                $xml = simplexml_load_file($api_address);
                $data = array();            
    
                if(isset($xml->Weather)){
    
                    $data['city'] = $xml->Weather->city;
                    
                    //天气状况
                    $data['status_day'] = $xml->Weather->status1;
                    $data['status_night'] = $xml->Weather->status2;
                    
                    //风级
                    $data['power_day'] = $xml->Weather->power1;
                    $data['power_night'] = $xml->Weather->power2;
                    
                    //温度
                    $data['temperature_day'] = $xml->Weather->temperature1;
                    $data['temperature_night'] = $xml->Weather->temperature2;
                    
                    //日期
                    $data['savedate_weather'] = $xml->Weather->savedate_weather;
                    
                    $return[] = $data;
                }else{
                    return false;
                    exit;
                }
            }
            
            return $return;
        }
        
        
        //过滤相关字眼
        private  static function filter($city_name)
        {
            if(strstr($city_name, "自治州")){
                
                return false;exit;
            
            }
            
            $filter_arr = array("市", "县", "地区");
            
            foreach ($filter_arr as $item){
                if(strstr($city_name, $item)){
                    $city_name = str_replace($item, "", $city_name);
                    break;
                }
            }
            
            $city_name = iconv('utf-8', "gb2312", $city_name);
            
            return urlencode($city_name);
        
        } 
    
    }
    
    

    调用实例:

     $weather=new Weather(7); //不传默认0,传正整数,获取最近几天天气
    print_R($weather->getXmlInfo("杭州"));
    
    

    返回数据:

    Paste_Image.png

    相关文章

      网友评论

          本文标题:新浪天气API接口获取最近几天天气数据!

          本文链接:https://www.haomeiwen.com/subject/dyavlxtx.html