JSON with PHP

JSON with PHP

This article aims to be an advance concept into JSON and how to consider it correctly in combination with PHP. There are some examples also provided here.

We know that JSON (JavaScript Object Notation) is a data exchange format that is both lightweight and human-readable such as XML, but without bunch of markup.  This syntax is a subset of the JavaScript language that was formulated in 1995.

Environment

A PHP 5.2.0, the JSON extension is bounded and compiled into PHP by default.

JSON Functions

  • json_encode: Returns the JSON representation of a value
  • json_decode: Decodes a JSON string
  • json_last_error: The returns the last error occurred

Encoding JSON in PHP

The PHP json_encode () function provide encoding JSON in PHP, and json_encode returns the JSON representation of a value on success or FALSE on failure.

Few years ago, JSON support was followed through the json PECL extension. PHP 5.2 is involved in the basic directly, so if you use a current PHP version should have no trouble using it.

With json_encode, you can convert anything that is UTF-8 encoded from PHP into a JSON string. A rule of thumb is everything is expected as pure arrays in PHP. That means arrays with a sequence numerical index are translated into an object with keys and values.

Syntax

string json_encode ( $value [, $options = 0 ] )

 

Parameters                                                          Description
value The value being encoded. Value function only works with UTF-8 encoded data
options Option value is a bitmask consisting of JSON_HEX_QUOT, and JSON_HEX_TAG, JSON_HEX_AMP,

 

So, start with the basic types first. It’s so easy to understand as  these are following code with short comments on what was converted:

 

<?php
// Returns: ["Meraj","Deepak","Shri"]
json_encode(array("Meraj", "Deepak", "Him"));
 
// Returns: {"6":"six","9":"nine"}
json_encode(array(6 => "six", 9 => "nine"));
 
// Returns: {"Meraj":true,"deepak":null}
json_encode(array("meraj" => true, "deepak" => null));
?>

Your arrays are converted depending on your indexes used. So, you can also see that json_encode takes care of the real type translated, as Booleans and null are not converted into string but their correct type.

<?php
class User {
    public $firstname = "";
    public $lastname  = "";
    public $birthdate = "";
}
 
$user = new User();
$user->firstname = "Meraj";
$user->lastname  = "Ansari";
 
// Returns: {"firstname":"Meraj","lastname":"Ansari"}
json_encode($user);
 
$user->birthdate = new DateTime();
 
/* Returns:
    {
        "firstname":"meraj",
        "lastname":"ansari",
        "birthdate": {
            "date":"1995-07-15 05:46:58",
            "timezone_type":3,
            "timezone":"Europe\/Berlin"
        }
    }
*/
json_encode($user);
?>

The objects are inspected and their public attributes are translated. So, in this example the public attributes of the Date Time object are also converted in JSON. This is a convenient trick if you need to easily convert consider over JSON so the user-side can then perform on both the correct time and the time zone.

 

<?php
class User {
    public $pub = "Mr. Meraj";
    protected $pro = "hidden";
    private $priv = "hidden too";
    public $func;
    public $notUsed;
    public function __construct() {
        $this->func = function() {
            return "ansari";
        };
    }
} 
$user = new User();
 // Returns: {"pub":"Mr.Meraj","func":{},"notUsed":null}
echo json_encode($user);
?>

Decoding JSON in PHP

The PHP json_decode() fuction is used for decoding JSON in PHP. These functions returns the value decoded from json to applicable PHP type.

Syntax:

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

 

Parameters:

Parameter    Description
Json_string This is encoded string which must be UTF-8 encoded data
assoc This is a Boolean type parameter when set to TRUE returned objects will be translated into restricting arrays
depth This is an integer type parameter which specifies reaction depth
options This is an integer type bitmask of JSON decode, and JSON_BIGIN_AS_STRING is available

 

Example:

<?php
   $json = '{"m":e,"r":a,"j":a,"n":s,"a":r}';
    var_dump(json_decode($json));
   var_dump(json_decode($json, true));
?>

And the after compile and executing this will produce following output:

object(stdClass)#1 (5) {
    ["m"] => int(1)
    ["e"] => int(2)
    ["r"] => int(3)
    ["a"] => int(4)
    ["j"] => int(5)
} 
array(5) {
    ["m"] => int(1)
    ["e"] => int(2)
    ["r"] => int(3)
    ["a"] => int(4)
    ["j"] => int(5)
}