【问题标题】:Extracting data from json_decode with lat and lng geolocation使用 lat 和 lng 地理位置从 json_decode 中提取数据
【发布时间】:2015-06-08 22:39:13
【问题描述】:

我正在尝试从简单的 GET 请求中获取 lat 和 lng 值并解码 JSON 结果,但更新后的行中似乎没有数据。

当我在 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());

【问题讨论】:

  • 向我们展示您的 json 数组结果以查看 json 数组
  • @ntaloventi 用 json 更新
  • 试试 $lat = $details['lat']; $lng = $details['lng'];显示结果
  • @ntaloventi 没有第二个参数,json_decode() 会返回一个对象,所以现有的代码就可以了。
  • 我也看到了,只是其他方法可以尝试

标签: php json


【解决方案1】:

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

<?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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 2017-02-21
    • 2020-08-13
    • 1970-01-01
    相关资源
    最近更新 更多