1. 程式人生 > >php定位並且獲取天氣信息

php定位並且獲取天氣信息

location php定位 city ext ons print map res func

 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;

php定位並且獲取天氣信息