【发布时间】:2017-02-05 09:08:09
【问题描述】:
我在 freegeoip.net 上摆弄,试图为我的访问者的 IP 获取更多信息。我可以成功检索用户 IP 的数组信息,但似乎无法将数组分开并获取 IP、城市、国家代码等的各个变量。
数组结果:
Array ( [ip] => 77.99.179.98 [country_code] => GB [country_name] => United Kingdom [region_code] => ENG [region_name] => England [city] => Gloucester [zip_code] => GL1 [time_zone] => Europe/London [latitude] => 51.8333 [longitude] => -2.25 [metro_code] => 0 )
PHP
<?php
$ip = "77.99.179.98";
$geoip = json_decode(file_get_contents('http://freegeoip.net/json/'.$ip), true);
print_r($geoip);
foreach ($geoip as $result) {
echo $result['ip']."<br>";
}
?>
编辑:
我现在收到Warning: Illegal string offset 'ip' in ... on line 9 错误,但确实得到了返回的 IP 地址的第一个数字... wth?
【问题讨论】:
-
数组结果是什么?那是
$geoip的内容吗? -
是的,见
foreach($geoip as $result) { -
好的,所以你必须使用
json_decode($geoip, true)解码它们 -$geoip json_decode(file_get_contents('http://freegeoip.net/json/'.$ip), true); -
@BubbleHacker 也不起作用,在执行
echo $result['ip']."<br>";时,我在返回 IP 地址的第一个数字时收到Warning: Illegal string offset 'ip' in ... on line 9错误...