This article is going to explain on how to use JSON with PHP.  PHP 5.2.0 supports JSON out of the box. So, when you install PHP, JSON support is automatically installed and you don't need any installation and configuration in addition.

JSON supports three PHP functions: json_decode, json_encode and json_last_error. We will discuss all of these functions with examples in the following section of this page. Let’s take a brief idea about these functions.

Syntax: mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )


$json ->   The json string being decoded. This function only works with UTF-8 encoded data.

$assoc -> When TRUE, returned objects will be converted into associative arrays.

$depth -> User specified recursion depth.

$options -> Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported (default is to cast large integers as floats)


json_decode() function decodes a JSON string. Suppose you have obtained some data in JSON format and you want to convert it into PHP variable for the purpose of presenting that data to user or use it for further programming, you have to use this function.

Example:  In this example I’m just creating a function with GetJsonFeed() which return the decode value of passed string.

 <!--To change this template, choose Tools | Templates

and open the template in the editor.


<!DOCTYPE html>



        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

        <title>JSON | Decode | Example</title>




            function GetJsonFeed($url)


                $feed = file_get_contents($url);

                return json_decode($feed);


             $tweets = GetJsonFeed("");





                 echo $tweets -> text;






Json_encode returns a string containing the JSON representation of value. This function is used to transform array and objects to JSON format.

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


$value -> Represents the value to encode;


Example: In this example, simply I’m creating a one dimensional array object and pass this to json_encode function.


             // Declare object of one dimensional array

                $arr = array('a1' => 1, 'b1' => 2, 'c1' => 3, 'd1' => 4, 'e1' => 5);

               // Encode this array object

                echo json_encode($arr);



While working on encoding or decoding JSON, if an error occur, json_last_error() function returns the last error. Json_last_error() function returns the integer value.

Syntax: int json_last_error();

This is the complete description on JSON functions which is widely used in PHP or how we can use JSON with PHP.

  Modified On Nov-30-2017 12:08:28 AM

Leave Comment