一.主要原理是 解析百度查询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'));
效果: