我需要获得用户的当前位置并将其保存到数据库中。我在PHP和来自ipinfo.io的Js中有一个小片段
但是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)我正在当地进行测试,我的国家是菲律宾。
发布于 2016-09-14 21:16:30
我不认为你会让你的城市和你的国家从这个网址上得到“本地主机”。你能在本地主机之外的服务器上测试它吗?我发现,当我在本地主机上测试时,我得到了与您相同的字段数,而'city‘和’AU‘中的"null“与'country’中的"AU”一样。但是,当我将它移到一个托管的测试服务器上时,我得到了以下内容(我已经编辑了我的“真实”数据):
对象(StdClass)#1 (8) { "ip"=>字符串(10) "99.99.99.99“”主机名“=> string(35) "99-99-99-99.dhcp.leds.tx.charter.com”“城市”=> string(10) "My City“区域”=> string(7)“"My”"country"=> string(2) =>string(2) "loc"=> string(16) "99.9999“,-99.9999“org"=>字符串(30)”“邮政”=>字符串“(5) "99999”}。
因此您会注意到,它还应该返回"region“、"org”和“test”,这在我的托管测试平台上是这样做的。在"localhost“上,它将这些字段完全排除在返回的内容之外(我做了一个var_dump,它们不在那里)。如果打开了E_NOTICE,您将在日志文件中看到警告,如果您正在使用这些字段(我正在使用它们),这些字段将不会返回。希望这能有所帮助。
https://stackoverflow.com/questions/36880049
复制相似问题