代码之家  ›  专栏  ›  技术社区  ›  Martin Mbae

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

  •  0
  • Martin Mbae  · 技术社区  · 5 年前

    <?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 回复  |  直到 5 年前
        1
  •  1
  •   shawn    5 年前

    文件内容不是有效的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
  •   Murzid    5 年前
    1. 请再次发布您的PHP代码
        3
  •  1
  •   Suraj Kumar zip    5 年前

    我认为在JSON文件中需要一个括号对,如下所示

    [
    {},
    {}
    ]