在許多網站應用中,依造訪者的 IP 判斷所在城市是很實用的功能。本文示範如何藉由新浪提供的 IP 查詢介面,分別用 Node.js 與 PHP 取得地理位置資訊。
Node.js 透過 http 模組發出請求,並以回呼函式處理結果:
var http = require('http');
var util = require('util');
var getIpInfo = function(ip, cb) {
var sina_server = 'https://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));
})
回傳結果為一個 JSON 物件,包含國家、省份、城市、ISP 等欄位,例如 city 為「徐州」、province 為「江蘇」、isp 為「電信」。
PHP 版本更為簡潔,直接用 file_get_contents 抓取資料,再以 json_decode 解析:
<?
$ip = "220.181.111.85";
$url = "https://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=$ip";
$data = file_get_contents($url);
$result = json_decode($data);
echo "城市:" . $result->city . "<br>";
print_r($result);
?>
輸出會得到一個 stdClass 物件,可直接以 $result->city 取出城市名稱。兩種語言的做法異曲同工,都能輕鬆完成 IP 地理定位的需求。