JSON encode and decode on PHP

Sharing is caring!

JSON makes dealing with data in your app exceptionally easy and manageable. The best part about JSON is you can look at it and understand it. It’s not like the confusing spaghetti DOM that you get with XML, it’s a lean minimal representation of your data. If you’re dealing with chunks of data in your app, you want to be using JSON.

So while your app will happily eat up all the JSON you can throw at it, you still need to make it in the first place – and/or have a server side app that is capable of reading it. If, like me, you use PHP to handle things on a server then things are pretty straightforward. You can use PHP’s json_encode and json_decode functions. Encode will take your arrays, or objects, and create a JSON string of your data. While decode will take a JSON string, sent from your app, and turn it into an array or object.

JSON encode function

In PHP, json_encode() is used to convert PHP supported data type into JSON formatted string to be returned as a result of JSON encode operation. This function accepts the following set of arguments.

  • Data to be encoded.
  • Options with JSON encode constants to reflect effects on encoding behavior.
  • Depth limit for performing recursive encoding with nested levels of input.

Predefined JSON Constants

For PHP JSON encode, the following list of constants will be used for the options parameter of json_encode() function.

    • JSON_HEX_TAG – Used to encode HTML content by replacing < and > symbol with u003C and u003E.
    • JSON_HEX_AMP – Used to encode data by replacing ampersand symbol (&) with u0026.
    • JSON_HEX_APOS – encode apostrophe (‘) with u0027.
    • JSON_HEX_QUOT – converts double quotes (“) into u0022.
    • JSON_FORCE_OBJECT – Using this, json_encode will return object for given input data except associative array.
    • JSON_NUMERIC_CHECK – PHP JSON encode function will return numbers as a result of encoding given number with string data type.
    • JSON_BIGINT_AS_STRING – This constant is used to convert the log integer value as string.
    • JSON_PRETTY_PRINT – pretty print is used for adding white space with the JSON formatted data.
    • JSON_UNESCAPED_SLASHES – It prevents from escaping slashes (/).
    • JSON_UNESCAPED_UNICODE – It prevents from escaping unicode characters.


The following example shows how to convert an array into JSON with PHP −

   $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
   echo json_encode($arr);

While executing, this will produce the following result −


The following example shows how the PHP objects can be converted into JSON −

   class Emp {
      public $name = "";
      public $hobbies  = "";
      public $birthdate = "";
   $e = new Emp();
   $e->name = "sachin";
   $e->hobbies  = "sports";
   $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p");
   $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));

   echo json_encode($e);

While executing, this will produce the following result −

{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}

Decoding JSON in PHP (json_decode)

PHP json_decode() function is used for decoding JSON in PHP. This function returns the value decoded from json to appropriate PHP type.


mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])


  • json_string − It is an encoded string which must be UTF-8 encoded data.
  • assoc − It is a boolean type parameter, when set to TRUE, returned objects will be converted into associative arrays.
  • depth − It is an integer type parameter which specifies recursion depth
  • options − It is an integer type bitmask of JSON decode, JSON_BIGINT_AS_STRING is supported.


The following example shows how PHP can be used to decode JSON objects −

   $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

   var_dump(json_decode($json, true));

While executing, it will produce the following result −

object(stdClass)#1 (5) {
   ["a"] => int(1)
   ["b"] => int(2)
   ["c"] => int(3)
   ["d"] => int(4)
   ["e"] => int(5)

array(5) {
   ["a"] => int(1)
   ["b"] => int(2)
   ["c"] => int(3)
   ["d"] => int(4)
   ["e"] => int(5)

Note: While passing associative array or object with key and value pair for json_decode(), the key value should be enclosed within double quotes. Otherwise, json_decode() will return NULL.

Comments 3

  • I used to be able to find good info from your content.

  • It is appropriate time to make a few plans for the longer term and it’s time to
    be happy. I have learn this post and if I may I desire to recommend you some interesting issues
    or tips. Perhaps you could write next articles relating to this article.
    I wish to read more issues approximately it!

  • Simply wish to say your article is as surprising. The clearness in your post is simply nice and i can assume you are an expert on this subject. Well with your permission allow me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please keep up the rewarding work.