1 /** 2 *获取天气预报信息 3 **/ 4 header("Content-type: text/html; charset=utf-8"); 5 class getWeather{ 6 private $ak; 7 8 public function __construct($ak){ 9 if($ak){ 10 $this->ak=$ak; 11 } else { 12 die('参数错误');exit; 13 } 14 15 } 16 17 /** 18 * 获取城市名称 19 * @param string $ip ip地址(必须为有效ip) 20 * return string $city 城市名称,如武汉 21 */ 22 public function getCity($ip=''){ 23 if(!$ip){ 24 $ip=$this->get_client_ip(); 25 } 26 $ak=$this->ak; 27 $content = file_get_contents("http://api.map.baidu.com/location/ip?ak=$ak&ip=$ip&coor=bd09ll"); 28 $json = json_decode($content,true); 29 if($json['status']==2){ 30 $city='武汉'; 31 }else{ 32 $address=$json['address']; 33 $cityarr=explode("|", $address); 34 $city=$cityarr['2'];//不带"市",如"武汉",而不是"武汉市" 35 } 36 return $city; 37 } 38 39 /** 40 * 获取天气预报信息 41 * @param string $city 城市名称,如武汉 42 * return array $data 天气信息 43 */ 44 public function weatherInfo($city=''){ 45 if(!$city){ 46 $city=$this->getCity(); 47 } 48 $host = "http://jisutqybmf.market.alicloudapi.com"; 49 $path = "/weather/query"; 50 $method = "GET"; 51 $appcode = "1215c3a301254ee79ca773ce9054f2ca";//阿里云appcode 52 $headers = array(); 53 array_push($headers, "Authorization:APPCODE " . $appcode); 54 $querys = "city=$city&citycode=citycode&cityid=cityid&ip=ip&location=location"; 55 $bodys = ""; 56 $url = $host . $path . "?" . $querys; 57 58 $curl = curl_init(); 59 curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); 60 curl_setopt($curl, CURLOPT_URL, $url); 61 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); 62 curl_setopt($curl, CURLOPT_FAILONERROR, false); 63 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 64 curl_setopt($curl, CURLOPT_HEADER, false); 65 if (1 == strpos("$".$host, "https://")) 66 { 67 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 68 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); 69 } 70 $result=curl_exec($curl); 71 $data=json_decode($result,true); 72 return $data; 73 } 74 /** 75 *获取ip 76 */ 77 public function get_client_ip(){ 78 if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")){ 79 $ip = getenv("HTTP_CLIENT_IP"); 80 }else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")){ 81 $ip = getenv("HTTP_X_FORWARDED_FOR"); 82 }else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) 83 $ip = getenv("REMOTE_ADDR"); 84 else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) 85 $ip = $_SERVER['REMOTE_ADDR']; 86 else 87 $ip = "unknown"; 88 return($ip); 89 } 90 } 91 $baiduak='CiEwAVN72cVAuHLzNRAMjzpY';//百度地图api的密钥 92 $wea=new getWeather($baiduak); 93 $json=$wea->weatherInfo(); 94 print_r($json);exit;