標籤:pre 地址 com cti location htm odi pass .com
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 *擷取ip50 */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 else61 $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定位並且擷取天氣資訊