Node.js and PHP's approach to obtaining geographic location from IP
Last Update:2017-02-28
Source: Internet
Author: User
This article mainly introduces the Node.js and PHP based on IP access to geographical location, through the Sina interface based on IP address to obtain the city, the need for friends can refer to the next, node.js implementation code code 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 &N Bsp if (code = =) { Res.on (' Data ', function (data) { & nbsp try { CB (NULL, Json.parse (data) ); } catch (Err) { & nbsp CB (ERR); &NBSp }); } else { CB ({code:code}); &N Bsp } }). On (' Error ', function (e) {CB (e);}); }; Getipinfo (' 220.181.111.85 ', function (err, msg) { Console.log (' City: ' + msg.city); CONSOL E.log (' msg: ' + util.inspect (msg, True, 8)); The result of the request: the code is as follows: City: Xuzhou { "ret": 1, "start": "49.68.0.0", "End": "49.68.255.255", & nbsp "Country": "China", "province": "Jiangsu", "City": "Xuzhou", "district": "", & nbsp "ISP": "Telecom", "type": "", "desc": "" "Two, PHP implementation code 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. "<br>"; Print_r ($result); ?> Request Result: The code is as follows: City: Xuzhou StdClass Object ( [ret] => 1 [start] => 49.68.0.0 [end] => 49.68.255.255 [C Ountry] => China [province] => Jiangsu [City] => Xuzhou [district] => &nbs P [ISP] => telecom [type] => [desc] =>)