0

This is my JSON file which I get from an external link:

[  
   {  
      "Id":441,
      "Name":"Gary"
   },
   {  
      "Id":1864,
      "Name":"Bob"
   }
]

When I try and display the Id and Name, I receive the error:

Notice: Trying to get property of non-object

$file = file_get_contents('http://linktojson.com');
$decode = json_decode($file, false);
$name = $decode->Name;
$id = $decode->Id;

echo $name;
echo $id;

1 Answer 1

2

Your json data has nested objects. So you need to access it like this:

$decode[0]->Name;

See here: https://3v4l.org/2aY22


Seeing as you have multiple objects with the same structure, you probably want to loop over them, like this:

foreach($decode AS $person) {
    echo $person->Id . ": " . $person->Name;
}

Side note: it really helps to examine your data structure if you're having trouble navigating it. Just doing a var_dump($decode); shows you quite clearly how it is structured and how you need to access it!

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, that's it! Thanks very much. Also, it only displays the first result. Is it possible to use a foreach loop to display them all?

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.