How to Encode, Decode and Use JSON Data in PHP

JSON is a popular way of storing and sending data because it can easily be interpreted by many programming languages, including PHP. If you are using an API, there is a good chance that you will get a response from the server containing JSON data.

 

In this tutorial, we will learn how to encode, decode and use JSON data in PHP with the json_decode and json_encode functions.

 

How to Decode JSON Data

In order to use JSON encoded data in PHP, it will have to be converted into a PHP variable. This is done using the native json_decode function. Depending on the type of data the JSON contains, you will most likely have a collection of objects and arrays in the newly created variable.

 

Let's say we have some JSON data located in a file here:

https://www.skillsugar.com/examples/json/example_1.json

 

{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red"
}

 

We can download it using file_get_contents before decoding the data into a PHP object with json_decode.

 

$json = file_get_contents('https://www.skillsugar.com/examples/json/example_1.json');

$data = json_decode($json);

print_r($data);
stdClass Object ( [fruit] => Apple [size] => Large [color] => Red )

 

How to Use Decoded JSON in PHP

Once JSON has been decoded it can be accessed like any other object or array. Let's look at how to access objects and arrays with a couple of examples.

 

{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red"
}

 

The above JSON example is an object with a list of properties; fruit, size and color. To access the contents of a property we can use the -> access modifier followed by the name of the property.

 

$json = file_get_contents('https://www.skillsugar.com/examples/json/example_1.json');

$data = json_decode($json);

echo $data->fruit;
Apple

 

Let's try accessing more complex JSON data.

https://www.skillsugar.com/examples/json/example_2.json

 

{
   "firstName": "Joe",
   "lastName": "Jackson",
   "gender": "male",
   "age": 28,
   "address": {
       "streetAddress": "101",
       "city": "San Diego",
       "state": "CA"
   },
   "phoneNumbers": [
       { "type": "home", "number": "7349282382" }
   ]
}

 

The above JSON is an object containing properties with different types of data, the first four are strings but the address property contains a nested object and the phoneNumbers property contains an array of objects.

 

$json = file_get_contents('https://www.skillsugar.com/examples/json/example_2.json');

$data = json_decode($json);

echo $data->firstName;

 

To access the city property of the address object, nest the -> access modifiers.

 

echo $data->address->city;
San Diego

 

To access objects in the phoneNumbers array, pass the key of the object inside [] (square brackets) followed by -> the name of the property.

 

echo $data->phoneNumbers['0']->number;
7349282382

 

 

json_decode to Array

To decode JSON data into an array in PHP pass true as the second argument of json_decode.

 

$json = file_get_contents('https://www.skillsugar.com/examples/json/example_1.json');

$array = json_decode($json, true);

print_r($array);
Array ( [fruit] => Apple [size] => Large [color] => Red )

 

Set JSON Decode Recursion Depth

To set the JSON decode to a specific recursion depth, pass a numerical depth as the third argument of json_decode. This value must be the same as the actual depth or null will be returned.

 

{
    "fruit": "Apple",
    "property": {
	"data": "hello",
	  "property": {
	      "property": {
		  "data": "Hello"
	      }
	  }
    } 
}
$json = file_get_contents('https://www.skillsugar.com/examples/json/example_3.json');

$data = json_decode($json, false, 6);

print_r($data);

 

Encoding JSON Data

Once you have finished working with the data you may want to encode it back to JSON for saving to a file or to upload it elsewhere. We can do this using the json_encode PHP function.

 

$json = file_get_contents('https://www.skillsugar.com/examples/json/example_3.json');

$data = json_decode($json);

$json_out = json_encode($json);
"{\n \"fruit\": \"Apple\",\n \"property\": {\n\t\"data\": \"hello\",\n\t\"property\": {\n\t \"property\": {\n\t\t\"data\": \"Hello\"\n\t }\n\t}\n } \n}\n"

 

Conclusion

You now know how to decode JSON data from a file, use the converted JSON data in PHP and encode the data back into JSON.

json data array object