2016-04-27 120 views
1

我需要获取用户的当前位置并将其保存到数据库。我有这个小的代码片段在PHP和Js从ipinfo.io通过ip地址获取用户位置 - ipinfo.io

但PHP代码不起作用,js版本。

$ip = $_SERVER['REMOTE_ADDR']; 
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json")); 
echo $details->city; // -> outputs nothing 


<script> 
    $.get("http://ipinfo.io", function(response) { 
    console.log(response.city);//logged my current city 
    }, "jsonp"); 
</script> 

任何想法如何实现PHP版本?

更新

我试图

var_dump($details) 

显示我

object(stdClass)[1] 
    public 'ip' => string '::1' (length=3) 
    public 'hostname' => string 'localhost' (length=9) 
    public 'city' => null 
    public 'country' => string 'AU' (length=2) 
    public 'loc' => string '-27.0000,133.0000' (length=17) 

我在本地主机测试它与我的国家是菲律宾

+0

可能重复[如何从PHP中的ipinfo.io中获取位置?](http://stackoverflow.com/questions/28012011/how-to-obtain-location-from-ipinfo-io-in-php) – chris85

+0

'var_dump($ details)'并检查城市的价值。 – Harikrishnan

回答

0

你不会让你的城市和你的国家在“本地主机”上米这个网址,我不认为。你可以在除localhost之外的服务器上测试它吗?我发现,当我在本地主机上测试时,我获得了相同数量的字段,并且像您一样在“城市”和“国家”中获得了“空白”。但是当我将它移动到托管测试服务器时,我得到了这个(我编辑了我的'真实'数据):

object(stdClass)#1(8){[“ip”] => string( 10)“99.99.99.99”[“hostname”] => string(35)“99-99-99-99.dhcp.leds.tx.charter.com”[“city”] => string(10)“My城市“[”region“] => string(7)”My State“[”country“] => string(2)”US“[”loc“] => string(16)”99.9999,-99.9999“[” org“] => string(30)”Blah Blah Blah Communications“[”postal“] => string(5)”99999“}。

所以你注意到它也应该返回它在我的托管测试平台上做的“region”,“org”和“postal”。在“localhost”上,它将这些字段完全从返回的内容中删除(我做了一个var_dump,但它们不在那里)。如果您启用了E_NOTICE,那么如果您正在使用它们(和我),那么您将在日志文件中看到未返回的字段的警告。 希望这有助于。