How To Encode & Decode JSON Data In PHP With Examples

PHP ships out of the box with some great native functions for working with JSON (JavaScript Object Notation), specifically json_encode() and json_decode(). These two JSON helper functions are particularly dedicated to encoding and decoding JSON data. Encode and decode functions in PHP are usually used with one of the following types; string and array.

In this tutorial-based article, we will learn about the json_encode() and json_decode() functions, what parameters they use, and finally how to utilize them in real-life code.

A quick introduction to json_encode() & json_decode()

Let’s first look at json_encode(), this function essentially attempts to convert any particular value into a representation of JSON. This is usually in the form of a string or most commonly an array.

The encode function has 3 parameters –

  • The value to be converted, for example, an array.
  • An optional options value which, uses a range of PHP constants to pretty much format the data returned.
  • An optional depth integer, instructing the function of how ‘nested’ the value you are passing in. Again, this is optional.

Now json_decode() on the other hand, has a completely different goal, which is to only attempt to convert a JSON string to a PHP object or array. The decode function has the following parameters

  • A string in the form of JSON data.
  • An optional Assoc boolean to instruct whether to bypass conversion to an object and to produce an associative array instead.
  • An optional depth integer to specify any user recursion depth if required.
  • An optional options parameter that takes some of the PHP constants available.

Now we’ve had an introduction to the functions let’s get our hands messy with some coding examples.

Encoding JSON data example

Let us build a dummy data array that is prepared for encoding into properly formatted JSON.

PHP Code

$myArray = ["myKey1" => "myValue1", "myKey2" => "myValue2", "myKey3" => "myValue3"];

Now, we have an array of data which is of an array type, If we take a quick look at this to see its structure below you will see it resembles nothing to JSON.

 

dummy data example array

Now, let’s use the json_encode() function to completely transform the array.

PHP Code

$myArray = ["myKey1" => "myValue1", "myKey2" => "myValue2", "myKey3" => "myValue3"];

echo json_encode($myArray);

Output

{"myKey1":"myValue1","myKey2":"myValue2","myKey3":"myValue3"}

The output is of perfect JSON data extracted and transformed from the array variable. If we were to check this with a tool like JSONLint, it would return valid JSON, perfect!

This method of encoding works similarly with a more advanced array with nesting for example.

Decoding JSON data example

Now let’s flip it the other way, we have a string in the form of JSON, but we want to make it usable in our project.

First up, we need to define the string

$myJsonString = '[{ "id": 1, "first_name": "Shanda", "last_name": "Tailby", "email": "stailby0@mapy.cz", "gender": "Female", "ip_address": "68.122.122.74"}, { "id": 2,"first_name": "Denny","last_name": "Plewright","email": "dplewright1@seesaa.net", "gender": "Female", "ip_address": "110.14.115.34"}]';

Now if we were to print this variable in our page, it would return exactly like above with the type of string. This of course, for what we are trying to achieve is useless. So, let’s go ahead and convert it. I will use two methods of conversion, one to a PHP object and the other to an array.

Decoding JSON as an array of Objects
$myJsonString = '[{ "id": 1, "first_name": "Shanda", "last_name": "Tailby", "email": "stailby0@mapy.cz", "gender": "Female", "ip_address": "68.122.122.74"}, { "id": 2,"first_name": "Denny","last_name": "Plewright","email": "dplewright1@seesaa.net", "gender": "Female", "ip_address": "110.14.115.34"}]';

$myObject = json_decode($myJsonString);

The new variable created with the decoding, $myObject will look like the output below

 

php array of objects example

Decoding JSON as an Associative Array

Now in this snippet, we utilize the optional assoc parameter and feed it a true boolean.

$myJsonString = '[{ "id": 1, "first_name": "Shanda", "last_name": "Tailby", "email": "stailby0@mapy.cz", "gender": "Female", "ip_address": "68.122.122.74"}, { "id": 2,"first_name": "Denny","last_name": "Plewright","email": "dplewright1@seesaa.net", "gender": "Female", "ip_address": "110.14.115.34"}]';

$myArray = json_decode($myJsonString, true);

As you can see, the json_decode() function is slightly different here, instructing the function to return the data as an associative array. Let’s take a look at the output of $myArray

 

php assoc array example

 

Further Reading

There are some useful references on the PHP documentation website that are worth a quick glance over. One especially is the JSON Constant documentation which relates to the potential options you can use within these function calls.

Summary

In general, these two functions have the following common uses –

Encoding is usually responsible for returning data from an API, it will convert an array datatype to JSON data for the consumer.

Decoding is usually responsible for converting raw JSON data in the form of a string into either a Object(StdClass)or an Array for further use in the application.

Hope this helps, as always, any questions, please drop them in the comments.

Posted in PHP

Leave a Reply