【问题标题】:Find json fields (geolocation from ip)查找 json 字段(来自 ip 的地理位置)
【发布时间】:2017-11-20 02:25:28
【问题描述】:

我正在尝试从 json 文档中分别找到字段 latitudelongitude,其中包含基于您的 IP 地址的访问者的一些地理位置信息,其中包含以下代码,但是好像不行:

$User_Latitude = $jsondata["latitude"];
$User_Longitude = $jsondata["longitude"];

我的错误在哪里?

完整代码:

$ip = $_SERVER['REMOTE_ADDR'];

function curl_get_contents($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

    $freegeoipjson = unserialize(curl_get_contents("http://freegeoip.net/json/". $ip .""));
    $jsondata = json_decode($freegeoipjson);
    $User_Latitude = $jsondata["latitude"];
    $User_Longitude = $jsondata["longitude"];

    $url = sprintf("https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s", $User_Latitude, $User_Longitude);
    $content = curl_get_contents($url); // get json content
    $metadata = json_decode($content, true); //json decoder
    if(count($metadata['results']) > 0)
    {
        $result = $metadata['results'][0];
        $User_location=$result['formatted_address']; // Address into normalize format.
    }
    echo $User_location;

【问题讨论】:

    标签: php json geolocation


    【解决方案1】:

    如果您从 curl 函数中获取正确的数据,则需要进行两项更改:

    1. 看起来您不需要反序列化调用(返回的数据在我看来没有序列化)
    2. 将第二个“true”参数传递给 json_decode 函数,以确保您实际上在 $jsondata 变量中获得了一个数组。

    这是修改后的两行:

    $freegeoipjson = curl_get_contents("http://freegeoip.net/json/". $ip);
    $jsondata = json_decode($freegeoipjson, true);
    

    【讨论】:

    • 在我的情况下,如果我将 true 设置为 json_decode() 将失败。正确的是:$freegeoipjson = curl_get_contents("http://freegeoip.net/json/". $ip .""); $jsondata = json_decode($freegeoipjson);。请编辑您的答案,我将删除此评论。
    • 我不太明白,抱歉。你是说一切正常吗?我在没有第二个参数的情况下测试了 json_decode,但它没有按预期工作,因为您将返回一个对象而不是数组。
    • 似乎这些差异与您主机上的某些设置有关。但即便如此,我会接受你的回答。
    • 谢谢。那么,您的初始代码中出现错误的原因是什么?
    • unserialize 不必要并且必须像这样访问字段:$jsondata->latitude; $jsondata->longitude;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    相关资源
    最近更新 更多