【问题标题】:Get data from JSON file with PHP [duplicate]使用 PHP 从 JSON 文件中获取数据 [重复]
【发布时间】:2013-11-14 13:17:53
【问题描述】:

我正在尝试使用 PHP 从以下 JSON 文件中获取数据。我特别想要“temperatureMin”和“temperatureMax”。

这可能真的很简单,但我不知道该怎么做。我被困在 file_get_contents("file.json") 之后要做什么。一些帮助将不胜感激!

{
    "daily": {
        "summary": "No precipitation for the week; temperatures rising to 6° on Tuesday.",
        "icon": "clear-day",
        "data": [
            {
                "time": 1383458400,
                "summary": "Mostly cloudy throughout the day.",
                "icon": "partly-cloudy-day",
                "sunriseTime": 1383491266,
                "sunsetTime": 1383523844,
                "temperatureMin": -3.46,
                "temperatureMinTime": 1383544800,
                "temperatureMax": -1.12,
                "temperatureMaxTime": 1383458400,
            }
        ]
    }
}

【问题讨论】:

    标签: php json


    【解决方案1】:

    使用json_decode 将您的 JSON 转换为 PHP 数组。示例:

    $json = '{"a":"b"}';
    $array = json_decode($json, true);
    echo $array['a']; // b
    

    【讨论】:

      【解决方案2】:

      使用file_get_contents()获取JSON文件的内容:

      $str = file_get_contents('http://example.com/example.json/');
      

      现在使用 json_decode() 解码 JSON:

      $json = json_decode($str, true); // decode the JSON into an associative array
      

      您有一个包含所有信息的关联数组。要弄清楚如何访问您需要的值,您可以执行以下操作:

      echo '<pre>' . print_r($json, true) . '</pre>';
      

      这将以可读的格式打印出数组的内容。请注意,第二个参数设置为true 是为了让print_r() 知道输出应该是returned(而不是仅仅打印到屏幕上)。然后,您可以访问所需的元素,如下所示:

      $temperatureMin = $json['daily']['data'][0]['temperatureMin'];
      $temperatureMax = $json['daily']['data'][0]['temperatureMax'];
      

      或者根据需要循环遍历数组:

      foreach ($json['daily']['data'] as $field => $value) {
          // Use $field and $value here
      }
      

      Demo!

      【讨论】:

      • 谢谢!但我似乎对 JSON 中的度数符号有问题,我做错了什么吗?
      • “本周无降水;周二气温升至 6°。”包括度数符号 (°)。当我在我的网站上尝试时,这似乎会导致您的演示没有任何响应。
      • @HaroldDunn 愿意分享您的解决方案吗?我怀疑我可能有类似的问题...
      • @JonnyNineToes:尝试在脚本的最顶部设置header('charset=utf8');
      • @FrayneKonok:他们会对1 感到困惑。我认为最好展示正确的方法。我现在还添加了关于第二个参数的评论。
      【解决方案3】:
      Try:
      $data = file_get_contents ("file.json");
              $json = json_decode($data, true);
              foreach ($json as $key => $value) {
                  if (!is_array($value)) {
                      echo $key . '=>' . $value . '<br/>';
                  } else {
                      foreach ($value as $key => $val) {
                          echo $key . '=>' . $val . '<br/>';
                      }
                  }
              }
      

      【讨论】:

      • 三个、四个等维度数组呢?此外,OP 没有要求回显结果
      猜你喜欢
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 2018-05-13
      相关资源
      最近更新 更多