Home > Web Front-end > JS Tutorial > Node.js and PHP method to obtain geographical location based on IP_javascript skills

Node.js and PHP method to obtain geographical location based on IP_javascript skills

WBOY
Release: 2016-05-16 16:55:44
Original
1127 people have browsed it

1. Node.js implementation code

Copy code The code is as follows:

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

/**
* Obtain address information based on 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) {                                                                                                                                    ;                                                                                         ; });
}
}).on('error', function(e) { cb(e); });
};

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

Request result:



Copy code
The code is as follows:City: Xuzhou{ "ret": 1, "start": "49.68.0.0",
"end": "49.68.255.255",
"country": "China",
"province": "Jiangsu",
"city": "Xuzhou",
"district": "",
"isp": "Telecom",
"type": " ",
"desc": ""
}

2. PHP implementation code



Copy code
The code is as follows:$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 "City:" . $result- >city . "
";
print_r($result);

?>

Request result:



Copy code
The code is as follows:City: XuzhoustdClass Object( [ret] => 1
[start ] => 49.68.0.0
[end] => 49.68.255.255
[country] => China
[province] => Jiangsu
[city] => Xuzhou
[district] =>
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template