
We access the China array object as below: " Įcho "Code: ".$data."" But when accessing the array items, we start counting from 0, hence the index of China in the array is 2. For example, china is in the third position. To access the values of a country in the example above, you just have to know its object position in the array. You may have a large JSON object made of an array of objects, like in the example below: Looping through an object of objects with foreach() The easiest way of accessing all the data is decoding the object as an associative array.Įcho "First Name: ".$data."" Įcho "Email Address: ".$data."" In the above example, the " address" has an object as its value while " siblings" has an array value comprising of objects. Accessing data in a nested JSON objectĪ JSON object may comprise of json objects and arrays as the values in its name-value pairs such as in the example below: You access the data as in any other PHP associative array as in the example below:
This is the same as the name in the name-value pair in JSON object eg $data->firstName. To access the PHP object data, you use the object operator ( ->) after the object name, followed by the key of the key-value pair. We use the built-in function json_decode() to convert the JSON string to the appropriate data type such as an object or an array.
#Php json decode as array full#
If the json file and the PHP file accessing it are in the same website, we can use relative path instead of the full file URL. Similar to POST or GET request, we use file_get_contents() but instead of having “php://input”, we use the file path.įor example, if we have a JSON file with path " ", we can access its data as below:
#Php json decode as array how to#
In this post, we will cover how to decode a JSON object and access its data in PHP.īelow is an example of a simple JSON object: It is the most popular and lightweight data-interchange format for web applications, and the de-facto format for the data exchange in RESTful web services requests and responses. It is easy to generate and parse in many programming languages.
