如何使用php获取BIG JSON数据

时间:2019-06-27 17:04:17

标签: php json

我有一个包含很大数据的JSON链接。因此,我无法使用json_decode($json);来解析$json = file_get_contents('_LINK_ '),因为它超出了内存限制,尽管我将memory_limit更改为64M。因此,我使用下面的方式/代码来解析它,我从这里php.net/manual/en/function.fgets.php中得到了它:

$json = @fopen("_URL", "r");

if ($json) {
   while (($json_data = stream_get_line($json, 4096)) !== false) {
       echo $json_data;
      //OR processing the $json_data
   }
}
if (!feof($json)) {
    echo "ERROR:...\n";
}
fclose($json);

我成功地做到了。这是回声$json_data之一的示例:

[{"A":"away team","C":"Competition name","D":"\/Date
(1561758400000)\/","H":"Home team","U":"hyperlink",...
}]

现在,我想获得values之类的away team, Competition name, \/Date(1561758400000)\/, Home team, hyperlink, ...。因此,我使用了var_dump(json_decode($json_data, true));。它返回NULL

我在 while循环中尝试了$rows = json_decode($json_data);,以便回显$row->A,但是失败了。

我也尝试过:

$json_data = json_decode($json,true);
foreach ($json_data as $row) {
  $a = $row['A'];
}

while循环内部,但也失败了,因为我猜想它没有成功解码。

我的期望是,我想将上述JSON DATA / STRING转换为 array 或我们可以使用的任何方式,以便获得值。

同样,我可以使用通过file_get_contents解析json文件的常规方式来实现。

感谢您的帮助。谢谢。

根据注释更新返回的数组,以更好地理解

[{"A":"Ukraine","C":"UEFA European Championship 2020",
"D":"\/Date(1567872000000)\/",
H":"Lithuania",
"NP":"",
"P":0,
"T":1,
"U":"hyperlink",
"V":1,"B1":22533,
"B2":22568,
"EE":[{"B":false,"C":13,"O":"","P":-1.5,"T":7},
    {"B":false,"C":1.001,"O":"","P":1.5,"T":8},
    {"B":false,"C":2.001,"O":"","P":1.8,"T":7},
    {the same as above}],
"HL":true,"I":198216465,
"S":"Football"},
{"A":"Moldova",...(to be continued the same as above)...
}],
"HL":true,
"I":198188444,
"S":"Football"
}]

1 个答案:

答案 0 :(得分:0)

规范化您的json

$json = '
    [
        {
            "A":"away team",
            "C":"Competition name",
            "D":"Date (1561758400000)",
            "H":"Home team",
            "U":"hyperlink"
        }
    ]';
    $json_data = json_decode($json, true);

    foreach ($json_data as $row) {
        echo $row['A'];
        echo $row['C'];
        echo $row['D'];
        echo $row['H'];
        echo $row['U'];
    }