当前位置:Gxlcms > JavaScript > Node.js和PHP根据ip获取地理位置的方法_javascript技巧

Node.js和PHP根据ip获取地理位置的方法_javascript技巧

时间:2021-07-01 10:21:17 帮助过:17人阅读

一、Node.js实现代码
代码如下:

var http = require('http');
var util = require('util');

/**
* 根据 ip 获取获取地址信息
*/
var getIpInfo = function(ip, cb) {
var sina_server = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=';
var url = sina_server + ip;
http.get(url, function(res) {
var code = res.statusCode;
if (code == 200) {
res.on('data', function(data) {
try {
cb(null, JSON.parse(data));
} catch (err) {
cb(err);
}
});
} else {
cb({ code: code });
}
}).on('error', function(e) { cb(e); });
};

getIpInfo('220.181.111.85', function(err, msg) {
console.log('城市: ' + msg.city);
console.log('msg: ' + util.inspect(msg, true, 8));
})

请求结果:
代码如下:
城市: 徐州
{
"ret": 1,
"start": "49.68.0.0",
"end": "49.68.255.255",
"country": "中国",
"province": "江苏",
"city": "徐州",
"district": "",
"isp": "电信",
"type": "",
"desc": ""
}

二、PHP实现代码
代码如下:

$ip = "220.181.111.85";
$url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=$ip";
$data = file_get_contents($url);
$result = json_decode($data);
echo "城市:" . $result->city . "
";
print_r($result);

?>

请求结果:
代码如下:
城市:徐州
stdClass Object
(
[ret] => 1
[start] => 49.68.0.0
[end] => 49.68.255.255
[country] => 中国
[province] => 江苏
[city] => 徐州
[district] =>
[isp] => 电信
[type] =>
[desc] =>
)

人气教程排行