通過php獲取ip所在地理位置

一.主要原理是 解析百度查詢ip返回的json結果

       /**
	* 獲取ip的地理位置 使用file_get_contents() 需要開啓ssl擴展
	* @param  string   $ip    ip地址
	* @return array    數組數據
	*/
	function getPointByIp($ip){
		if(!function_exists('curl_init')){
			die( '請先開啓curl擴展');
		}
		$arr = array();
		$arr['ip'] = $ip; 
	    //-------------百度ip查詢
		$url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={$ip}&co=&resource_id=6006&t=1422325640049&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110203130218356382102_1422320146335&_=1422320146337";
		//-------------設置支持ssl------------
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_REFERER, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		$result = iconv('GB2312', 'UTF-8', curl_exec($ch));
		if(is_null($result)){
			die('返回結果出錯');
			return;
		}
		$pattern = '/\(([\s\S]+?)\)/';
		if(!preg_match($pattern, $result, $outs)){
			die( '正則解析出錯');
			return;
		}
		$obj = json_decode($outs[1]);
		$arr['location'] = $obj->data[0]->location;
		return $arr;
	}
    var_dump(getPointByIp('120.36.191.37'));

效果:



發佈了24 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章