0

I am trying to decode a JSON file using PHP. This is the Code that I am using.

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

  $contendecoded = json_decode($content);

  print_r($contendecoded);

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

This is the result.json file

{"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"}

I am getting this error

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

The line 8 refereed by the error is

foreach ($contendecoded as $each) {

How do I solve this?

3
  • can you share your code written before the foreach? Commented Mar 18, 2019 at 3:55
  • I've edited the question Commented Mar 18, 2019 at 3:56
  • you json not in array format like [{},{}], try with '$contendecoded = array(json_decode($content))' Commented Mar 18, 2019 at 4:05

3 Answers 3

1

Your content of the file is NOT valid JSON.

You can refer this question (also answered by me) 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);
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is working even without editing the JSON. Kudos.
1
  1. Please post again your PHP code
  2. JSON code not valid (need bracket / parenthesis)

1 Comment

You saved my day. I am following a tutorial and I somehow forgot to add [] brackets over my JSONfile. It's now working. Thank you.
1

I think you need a bracket pair in the JSON file, like this

[
{},
{}
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.