How to decode JSON data and accessing the results in PHP

Today, In this blog we are going to learn “How to decode JSON data and accessing the results in PHP”.

JSON is not an array, an object, or a data structure. JSON is a text-based serialization format – so a fancy string, but still just a string. Decode it in PHP by using json_decode().

Suppose we have this JSON File.

How do we decode this JSON data in PHP and access the resulting data?

Accessing object properties

You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property.

Accessing array elements

You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0].

Iterate it with foreach loop.

You May Also Like:

Passing true as the second argument to json_decode()

When you do this, instead of objects you’ll get associative arrays – arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array[‘key’].

Don’t know how the data is structured

Read the documentation for whatever it is you’re getting the JSON from.

Look at the JSON – where you see curly brackets {} expect an object, where you see square brackets [] expect an array.

Hit the decoded data with a print_r():

and check the output:

It’ll tell you where you have objects, where you have arrays, along with the names and values of their members.

Few Points to remember:

  • json_decode requires the string to be a valid json else it will return NULL.
  • In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.
  • Make sure you pass in utf8 content, or json_decode may error out and just return a NULLvalue.

No Comment.