1 header("Content-type: text/html; charset=utf-8"); 2 class getWeather{ 3 private $ak; 4 5 public function __construct($ak){ 6 if($ak){ 7 $this->ak=$ak; 8 } else { 9 die(‘参数错误‘);exit; 10 } 11 12 } 13 14 /** 15 * 获取城市名称 16 * @param string $ip ip地址(必须为有效ip) 17 * return string $city 城市名称,如武汉 18 */ 19 public function getCity($ip=‘‘){ 20 if(!$ip){ 21 $ip=$this->get_client_ip(); 22 } 23 $ak=$this->ak; 24 $content = file_get_contents("http://api.map.baidu.com/location/ip?ak=$ak&ip=$ip&coor=bd09ll"); 25 $json = json_decode($content,true); 26 $address=$json[‘address‘]; 27 $cityarr=explode("|", $address); 28 $city=$cityarr[‘2‘];//不带"市",如"武汉",而不是"武汉市" 29 return $city; 30 } 31 32 /** 33 * 获取天气预报信息 34 * @param string $city 城市名称,如武汉 35 * return array $data 天气信息 36 */ 37 public function weatherInfo($city=‘‘){ 38 if(!$city){ 39 $city=$this->getCity(); 40 } 41 $content1=urlencode(mb_convert_encoding($city, ‘gb2312‘, ‘utf-8‘)); 42 $weather=file_get_contents("http://php.weather.sina.com.cn/xml.php?city=$content1&password=DJOYnieT8234jlsK&day=0"); 43 $ob= simplexml_load_string($weather); 44 $json = json_encode($ob); 45 $data = json_decode($json, true); 46 return $data; 47 } 48 /** 49 *获取ip 50 */ 51 public function get_client_ip(){ 52 if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")){ 53 $ip = getenv("HTTP_CLIENT_IP"); 54 }else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")){ 55 $ip = getenv("HTTP_X_FORWARDED_FOR"); 56 }else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) 57 $ip = getenv("REMOTE_ADDR"); 58 else if (isset($_SERVER[‘REMOTE_ADDR‘]) && $_SERVER[‘REMOTE_ADDR‘] && strcasecmp($_SERVER[‘REMOTE_ADDR‘], "unknown")) 59 $ip = $_SERVER[‘REMOTE_ADDR‘]; 60 else 61 $ip = "unknown"; 62 return($ip); 63 } 64 } 65 $baiduak=‘你的密钥‘;//百度地图api的密钥 66 $wea=new getWeather($baiduak); 67 $json=$wea->weatherInfo(); 68 print_r($json);exit;
时间: 2024-10-06 06:34:05