在php中解码JSON文件时出现无效的参数错误

时间:2019-03-18 03:53:02

标签: php json

我正在尝试使用PHP解码JSON文件。这是我正在使用的代码。

<?php
  $content =  file_get_contents('result.json');

  $contendecoded = json_decode($content);

  print_r($contendecoded);

  foreach ($contendecoded as $each) {
    # code...
    echo '<li>' .$each->Receiver. '</li>';
  }
  ?>

这是result.json文件

{"Sender":"254705537065","Receiver":"7528452889","Amount":"1","FName":"Martinique","AccessToken":"8XRTHN59NCHvUGAASGbK6IcCzYcn"},
{"Sender":"254705537065","Receiver":"6584238686","Amount":"2","FName":"Phillipines2","AccessToken":"O4wBFWPmFA8ayKGYahhpdCAW97mg"},
{"Sender":"254705537065","Receiver":"6584238686","Amount":"2","FName":"Phillipines2","AccessToken":"O4wBFWPmFA8ayKGYahhpdCAW97mg"},
{"Sender":"254705537065","Receiver":"6584238686","Amount":"36","FName":"Phillipines3","AccessToken":"O4wBFWPmFA8ayKGYahhpdCAW97mg"},
{"Sender":"254705537065","Receiver":"6584238686","Amount":"36","FName":"Phillipines3","AccessToken":"O4wBFWPmFA8ayKGYahhpdCAW97mg"}

我收到此错误

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\website\receive.php on line 8

错误引用的第8行是

foreach ($contendecoded as $each) {

我该如何解决?

3 个答案:

答案 0 :(得分:1)

  1. 请再次发布您的PHP代码
  2. JSON代码无效(需要括号/括号)

答案 1 :(得分:1)

您的文件内容不是有效的JSON。

您可以提出这个问题(我也回答了) Decoding multiple JSON objects in PHP

function json_decode_multi($s, $assoc = false, $depth = 512, $options = 0) {
    if(substr($s, -1) == ',')
        $s = substr($s, 0, -1);
    return json_decode("[$s]", $assoc, $depth, $options);
}

$content =  file_get_contents('result.json');
$contendecoded = json_decode_multi($content);
print_r($contendecoded);

答案 2 :(得分:1)

我认为您需要在JSON文件中添加一个括号对,

[
{},
{}
]