查找 json 个字段(来自 ip 的地理位置)
Find json fields (geolocation from ip)
我正在尝试从包含一些地理位置信息的 json 文档中分别找到字段 latitude 和 longitude基于您的 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;
如果您从 curl 函数返回正确的数据,则需要进行两项更改:
- 看起来你不需要反序列化调用(返回的数据对我来说没有序列化)
- 将第二个 "true" 参数传递给 json_decode 函数,以确保您实际上在 $jsondata 变量中得到一个数组。
这里是修改后的两行:
$freegeoipjson = curl_get_contents("http://freegeoip.net/json/". $ip);
$jsondata = json_decode($freegeoipjson, true);
我正在尝试从包含一些地理位置信息的 json 文档中分别找到字段 latitude 和 longitude基于您的 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;
如果您从 curl 函数返回正确的数据,则需要进行两项更改:
- 看起来你不需要反序列化调用(返回的数据对我来说没有序列化)
- 将第二个 "true" 参数传递给 json_decode 函数,以确保您实际上在 $jsondata 变量中得到一个数组。
这里是修改后的两行:
$freegeoipjson = curl_get_contents("http://freegeoip.net/json/". $ip);
$jsondata = json_decode($freegeoipjson, true);