【问题标题】:Read External JSON in PHP在 PHP 中读取外部 JSON
【发布时间】:2017-02-28 17:51:28
【问题描述】:

我正在尝试从 PHP 中读取 JSON,如下所示:

    [{
  "titulo": "DontAsk",
  "pais": "Austria",
  "country_iso": "AT",
  "direccion": "Mag. Th. Langmann Gmbh Landstrasse 4",
  "cp_ciudad": "A-2000 STOCKERAU",
  "lat": "48.385583",
  "long": "16.207823",
  "telefono": "43-2266-72554-11",
  "fax": "43-2266-72554-44",
  "web": "www.aaa.com"
}, {
  "titulo": "Other One",
  "pais": "Czech Republic",
  "country_iso": "CZ",
  "direccion": "Pod Cihelnou 6",
  "cp_ciudad": "664 161 00 PRAHA 6",
  "lat": "50.092605",
  "long": "14.312707",
  "telefono": "420 233 313 578",
  "fax": "420 233 313 582",
  "web": "www.bbb.com"
}]

JSON 没有错误,我尝试使用 JsonLint 并发现它很干净。 我有更多的插入,但我只插入了 2 个。

然后我尝试这样的代码行:

        $json = json_decode(file_get_contents($url), true);
    var_dump($json);

URL返回很好地检索URL,但是在var_dump中返回NULL

我看到了很多答案和问题,但没有找到答案。 有什么帮助吗?

读取 Json -> 在 PHP 中转换为数组 -> 检索数组

谢谢

【问题讨论】:

  • 你有什么问题?
  • 此 JSON 字符串已正确解析为 json_decode3v4l.org/3Qn0V 检查file_get_contents($url) 是否给你预期的结果。
  • 您基本上拥有一个执行多项任务并假设不会出错的单行程序。您需要进行错误检查。

标签: php arrays json decode file-get-contents


【解决方案1】:

上述代码中的 JSON 字符串 ($json) 是一个对象数组。也就是说,外层是一个数组字面量,其元素是对象字面量。默认情况下,json_decode 的结果将是一个数字索引的对象数组

$json = '[{
"titulo": "DontAsk",
"pais": "Austria",
"country_iso": "AT",
"direccion": "Mag. Th. Langmann Gmbh Landstrasse 4",
"cp_ciudad": "A-2000 STOCKERAU",
"lat": "48.385583",
"long": "16.207823",
"telefono": "43-2266-72554-11",
"fax": "43-2266-72554-44",
"web": "www.aaa.com"
}, {
"titulo": "Other One",
"pais": "Czech Republic",
"country_iso": "CZ",
"direccion": "Pod Cihelnou 6",
"cp_ciudad": "664 161 00 PRAHA 6",
"lat": "50.092605",
"long": "14.312707",
"telefono": "420 233 313 578",
"fax": "420 233 313 582",
"web": "www.bbb.com"
}]';
$data = json_decode($json);
echo $data[1]->titulo; 

为了您的参考,请检查此http://www.dyn-web.com/tutorials/php-js/json/decode.php

【讨论】:

    【解决方案2】:

    如果您想要的是一个关联数组以供以后使用 PHP,而不是对象数组(这是 json_decode 默认处理的),那么在函数的第二个参数上指定它,如下所示:

    $json = '[{
    "titulo": "DontAsk",
    "pais": "Austria",
    "country_iso": "AT",
    "direccion": "Mag. Th. Langmann Gmbh Landstrasse 4",
    "cp_ciudad": "A-2000 STOCKERAU",
    "lat": "48.385583",
    "long": "16.207823",
    "telefono": "43-2266-72554-11",
    "fax": "43-2266-72554-44",
    "web": "www.aaa.com"
    }, {
    "titulo": "Other One",
    "pais": "Czech Republic",
    "country_iso": "CZ",
    "direccion": "Pod Cihelnou 6",
    "cp_ciudad": "664 161 00 PRAHA 6",
    "lat": "50.092605",
    "long": "14.312707",
    "telefono": "420 233 313 578",
    "fax": "420 233 313 582",
    "web": "www.bbb.com"
    }]';
    
    $data = json_decode($json, true);
    var_dump($data['titulo']);
    

    但如果问题是它返回 NULL,请检查您的脚本是否获得了预期的输入(例如,您获得了一个可由 json_decode 解析的字符串)。

    【讨论】:

      猜你喜欢
      • 2021-06-03
      • 1970-01-01
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多