1 Header("content-type:text/html; Charset=utf-8 ");2 classgetweather{3 Private $ak;4 5 Public function__construct ($ak){6 if($ak){7 $this->ak=$ak;8}Else {9 die(' parameter error ');Exit;Ten } One A } - - /** the * Get city name - * @param string $IP IP address (must be a valid IP) - * Return string $city city name, e.g. Wuhan - */ + Public functionGetcity ($ip= ' '){ - if(!$ip){ + $ip=$this-get_client_ip (); A } at $ak=$this-AK; - $content=file_get_contents("http://api.map.baidu.com/location/ip?ak=$ak&ip=$ip&coor=bd09ll "); - $json= Json_decode ($content,true); - $address=$json[' Address ']; - $cityarr=Explode("|",$address); - $city=$cityarr[' 2 '];//without "City", such as "Wuhan", not "Wuhan " in return $city; - } to + /** - * Get weather information the * @param string $city city name, such as Wuhan * * Return Array $data weather information $ */Panax Notoginseng Public functionWeatherinfo ($city= ' '){ - if(!$city){ the $city=$this-getcity (); + } A $content 1=UrlEncode(Mb_convert_encoding ($city, ' gb2312 ', ' utf-8 ')); the $weather=file_get_contents("http://php.weather.sina.com.cn/xml.php?city=$content 1&password=djoyniet8234jlsk&day=0 "); + $ob=simplexml_load_string($weather); - $json= Json_encode ($ob); $ $data= Json_decode ($json,true); $ return $data; - } - /** the * Get IP - */Wuyi Public functionget_client_ip () { the if(getenv("Http_client_ip") &&strcasecmp(getenv("Http_client_ip"), "Unknown")){ - $ip=getenv("Http_client_ip"); Wu}Else if(getenv("Http_x_forwarded_for") &&strcasecmp(getenv("Http_x_forwarded_for"), "Unknown")){ - $ip=getenv("Http_x_forwarded_for"); About}Else if(getenv("REMOTE_ADDR") &&strcasecmp(getenv("REMOTE_ADDR"), "Unknown")) $ $ip=getenv("REMOTE_ADDR"); - Else if(isset($_server[' REMOTE_ADDR ']) &&$_server[' REMOTE_ADDR '] &&strcasecmp($_server[' REMOTE_ADDR '], "unknown")) - $ip=$_server[' REMOTE_ADDR ']; - Else A $ip= "Unknown"; + return($ip); the } - } $ $baiduak= ' Your secret key ';//Baidu Map API Key the $wea=NewGetWeather ($baiduak); the $json=$wea-weatherinfo (); the Print_r($json);Exit;
PHP location and get weather information