1 //天气预报 2 $ch = curl_init(); 3 $url = "http://www.baidu.com/home/other/data/weatherInfo?city=$city"; 4 5 // 添加apikey到header 6 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // 设置header(很重要,第二个参数填什么数字) 7 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 10); 8 // 执行HTTP请求 9 curl_setopt($ch, CURLOPT_URL, $url); 10 $res = curl_exec($ch); 11 $arr = (json_decode($res, true)["data"]['weather']['content']['tomorrow']); 12 $arr['temp'] = explode("~", $arr['temp']); 13 $array['city'] = $city; 14 $data['weather'] = $arr['condition']; 15 $data['l_tmp'] = (int)$arr['temp'][0]; 16 $data['h_tmp'] = (int)$arr['temp'][1];
1 //获取天气信息 2 public function get_weather() 3 { 4 $rules = ['city']; 5 if (true == self::is_empty($rules)) { 6 $city = I("post.city"); 7 $url="http://wthrcdn.etouch.cn/WeatherApi?city=$city"; 8 // $data=preg_replace('/<!--+.*-->/','',$data); 9 //把gbk格式转为utf-8 10 // $data = iconv('GBK','UTF-8', $data); 11 $curl=$this->curl_get($url,true); //下载天气网页内容并且解压 12 $xml=$this->FromXml($curl); //把xml转化为json格式 13 $array=$this->data($xml,$city); //拿到json格式获取需要的数据 14 $this->send($array); 15 } else { 16 $this->send("数据格式有误", 0); 17 } 18 } 19 20 21 /**将xml转为array 22 * @param $xml 23 * @return mixed 24 */ 25 function FromXml($xml) 26 { 27 if (empty($xml)) 28 return 0;//xml数据异常 29 libxml_disable_entity_loader(true); 30 return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); 31 } 32 33 function curl_get($url, $gzip=false){ 34 $curl = curl_init($url); 35 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上。 36 curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10); // 设置header(很重要,第二个参数填什么数字) 37 if($gzip) curl_setopt($curl, CURLOPT_ENCODING, "gzip"); //解压 38 $content = curl_exec($curl);// 运行cURL,请求网页 39 curl_close($curl); 40 return $content; 41 } 42 43 //需要的数据 44 public function data($data,$city){ 45 $array['city']=$city; 46 $array['wendu']=$data['wendu']; 47 if(!empty($data['environment']['pm25'])){ 48 $array['aqi']=$data['environment']['aqi']; 49 $array['pm25']=$data['environment']['pm25']; 50 $array['quality']=$data['environment']['quality']; 51 } 52 $array['high']=substr($data['forecast']['weather'][0]['high'],7,2); 53 $array['low']=substr($data['forecast']['weather'][0]['low'],7,2); 54 $array['type']=$data['forecast']['weather'][0]['day']['type']; 55 $array['zhishus']=$data['zhishus']['zhishu'][0]; 56 return $array; 57 }