发布于 2016-08-26 02:27:23 | 218 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Node.js教程,程序狗速度看过来!

Node.js 服务器端的JavaScript

Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台, 用来方便地搭建快速的 易于扩展的网络应用· Node.js 借助事件驱动, 非阻塞I/O 模型变得轻量和高效, 非常适合 运行在分布式设备 的 数据密集型 的实时应用


这篇文章主要介绍了Node.js和PHP根据ip获取地理位置的方法,通过新浪接口根据IP地址获取所在城市,需要的朋友可以参考下
一、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 . "<br>";
print_r($result);

?>

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



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务