【问题标题】:Consuming JSON API using PHP使用 PHP 使用 JSON API
【发布时间】:2020-09-09 12:56:25
【问题描述】:

我已经阅读并尝试了一些在其他帖子中发现的类似问题的代码,但我找不到解决方案。

我正在使用这个 API:https://api.ipma.pt/open-data/forecast/meteorology/cities/daily/1100900.json,它返回这个:

  {
      "owner": "IPMA",
      "country": "PT",
      "data": [
        {
          "precipitaProb": "0.0",
          "tMin": "12.6",
          "tMax": "24.0",
          "predWindDir": "N",
          "idWeatherType": 3,
          "classWindSpeed": 2,
          "longitude": "-8.8069",
          "forecastDate": "2020-05-22",
          "latitude": "39.7473"
        },
        {
          "precipitaProb": "0.0",
          "tMin": "13.1",
          "tMax": "24.2",
          "predWindDir": "N",
          "idWeatherType": 5,
          "classWindSpeed": 2,
          "longitude": "-8.8069",
          "forecastDate": "2020-05-23",
          "latitude": "39.7473"
        },
        {
          "precipitaProb": "0.0",
          "tMin": "12.8",
          "tMax": "26.5",
          "predWindDir": "NW",
          "idWeatherType": 2,
          "classWindSpeed": 1,
          "longitude": "-8.8069",
          "forecastDate": "2020-05-24",
          "latitude": "39.7473"
        },
        {
          "precipitaProb": "0.0",
          "tMin": "13.4",
          "tMax": "26.0",
          "predWindDir": "NW",
          "idWeatherType": 5,
          "classWindSpeed": 1,
          "longitude": "-8.8069",
          "forecastDate": "2020-05-25",
          "latitude": "39.7473"
        },
        {
          "precipitaProb": "3.0",
          "tMin": "16.3",
          "tMax": "31.7",
          "predWindDir": "E",
          "idWeatherType": 2,
          "classWindSpeed": 2,
          "longitude": "-8.8069",
          "forecastDate": "2020-05-26",
          "latitude": "39.7473"
        }
      ],
      "globalIdLocal": 1100900,
      "dataUpdate": "2020-05-22T14:31:04"
    }

我需要从“data”数组中获取几个值。

到目前为止,我有这个:

<?php

$api_url = file_get_contents('https://api.ipma.pt/open-data/forecast/meteorology/cities/daily/1100900.json');
$forecastLeiria = json_decode($api_url);

var_dump($forecastLeiria);

?>

即使 API 工作正常,也会返回 NULL

干杯!

【问题讨论】:

  • 奇数。相同的代码似乎对我有用。尝试转储 $api_url 看看会得到什么。
  • allow_url_fopen 开启了吗?
  • var_dump($api_url) 返回 bool(false)... 可能是问题所在。
  • 该行为没有其他合乎逻辑的解释;因为 URL 存在且 JSON 有效。
  • 好吧,我不知道如何解决这个问题。我会尝试使用 cURL 而不是 file_get_contents...

标签: php json api file-get-contents jsondecoder


【解决方案1】:

我已经尝试了您的代码,并且它在我这边运行良好。 此问题的一个可能原因可能是您的 PHP 配置。 请运行 phpinfo() ,滚动到核心部分并检查 allow_url_fopen 指令是否已打开。如果它关闭,那么您需要在 php.ini 配置文件中将其打开。 它是允许 PHP 脚本在 Internet 上打开公共文件的指令,因此会影响 file_get_contents 函数如何处理公共文件。

【讨论】:

  • 谢谢。我刚刚做了,allow_url_fopenON。仍然无法正常工作。 link
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2012-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多