【问题标题】:PHP - print GeoIP arrayPHP - 打印 GeoIP 数组
【发布时间】: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']."&lt;br&gt;"; 时,我在返回 IP 地址的第一个数字时收到 Warning: Illegal string offset 'ip' in ... on line 9 错误...

标签: php arrays freegeoip


【解决方案1】:

终于!

<?php
$ip = "77.99.179.98";

$ip_data = file_get_contents('http://freegeoip.net/json/'.$ip);
$data = json_decode($ip_data);

print_r($data);

echo "<br><br>";

echo htmlspecialchars($data->country_name);

?>

【讨论】:

    猜你喜欢
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 2018-07-04
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多