使用lat和lng地理位置从json_decode提取数据


Extracting data from json_decode with lat and lng geolocation

我试图从一个简单的get请求和解码JSON结果中获得lat和lng值,但在更新的行中似乎没有数据。

当我在URL中插入IP地址时,我可以看到有一个有效的lat和lng值,见下文。

JSON的例子:

{
    "country_name": "DENMARK",
    "country_code": "DK",
    "city": "Havdrup",
    "ip": "xx",
    "lat": "55.4333",
    "lng": "9.25"
}
代码:

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://api.hostip.info/get_json.php?ip={$ip}&position=true"));
$lat = $details->lat;
$lng = $details->lng;
$result_update_settings = mysqli_query(
    $con,
    "UPDATE users SET
        lat = '" . $lat . "',
        lng = '" . $lng . "'
    WHERE id = '" . $login_session . "'"
) or die(mysqli_error());

我首先声明,您应该打开错误报告,以发现可能出现的任何潜在问题。这可以通过在脚本的顶部添加以下内容来完成:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

尽量不要简化您的file_get_contents()调用。首先确保一切正常:

$json = file_get_contents("http://api.hostip.info/get_json.php?ip={$ip}&position=true");
$data = json_decode($json);
// you could print_r($data); here to see if you get what you requested.
$lat = $data->lat;
$lng = $data->lng;
// now echo, just to check if you actually get your values!
echo $lat . " & " . $lng;

你确定你的查询正在成功执行吗?

  • 查询后var_dump($result_update_settings);返回什么?
  • $login_session是什么