JSON

JSON with PHP

JSON with PHP

In this section, we see how to work with JSON using PHP. We can encode and decode JSON objects using PHP programming language. If you use PHP 5.2.0, then the JSON extension comes bundled and compiled into PHP.  JSON is commonly used to read data from a web server and display the data in a web page. Let see how to do that between the client and a PHP server. But before that, we briefly review the 3 most common functions used in PHP in relation to json.

  1. json_encode () function returns the JSON representation of a value.
  2. json_decode () is used to decode a JSON string.
  3. json_last_error () is used to get the last error occurred.

Let us see the use of each of these functions starting from json_encode. json_encode() does encoding  of JSON in PHP and it returns the JSON representation of a value on success or FALSE on failure. Its syntax is 

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

Its parameters are value and options. The <value> refers to actual value that is being encoded. You need to pass UTF-8 encoded data as any other encoding won't work. The <options> is a value that is a bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT. 

The following code displays employee record using json_encode().

<?php
$myObj = new employeeClass();
$myObj->fname = "Rita";
$myObj->lname = "Gupta";
$myObj->age = 30;
$myObj->employeecode = 5527104;
$myJSON = json_encode($myObj);
echo $myJSON;
?>

The output of this code snippet is as follows:

{"fname":"Rita","lname":"Gupta","age":30,employeecode:5527104}

Like singleton variables, we can convert PHP arrays into JSON using the PHP function json_encode(). See below :

<?php
$myVehiclesArr = array("Bicycle", "Rider", "Scooter", "Car");
$myVehicleJSON = json_encode($myVehiclesArr);
echo $myVehicleJSON;
?>

Its output will be shown below:

[Bicycle","Rider","Scooter","Car"]

Next, we move to PHP json_decode(). This function decodes JSON and returns the value decoded from json to appropriate PHP type. Its syntax is as follows:

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

Its parameters are json_string, assoc, depth and options. The <json_string> refers to an encoded string of the type UTF-8 encoded data. The <assoc> refers to a boolean type parameter that set returned objects into associative arrays (when assoc is True). The <depth> refers to an integer type parameter specifying the recursion depth. Finally, the <options> refers to an integer type bitmask of JSON decode (JSON_BIGINT_AS_STRING is supported). Let’s see this function in action

<?php
   $json = '{"India":"hi","USA":"en-us","UK":"en-gb","People's Republic of China":"zh","France":"fr"}';
   var_dump(json_decode($json));
   var_dump(json_decode($json, true));
?>

You’ll get the following output

object(stdClass)#1 (5) { ["India"]=> string(2) "hi" ["USA"]=> string(5) "en-us" ["UK"]=> string(5) "en-gb" ["Peoples Republic of China"]=> string(2) "zh" ["France"]=> string(2) "fr" } array(5) { ["India"]=> string(2) "hi" ["USA"]=> string(5) "en-us" ["UK"]=> string(5) "en-gb" ["Peoples Republic of China"]=> string(2) "zh" ["France"]=> string(2) "fr" }   

PHP json_last_error() function returns the last error occurred. Let us see it in an example. This example is trying to decode a JSON string that has a syntax error (the key gender is not written as a string). So json_last_error() will return JSON_ERROR_SYNTAX. 

<?php
// A json string with syntax error
$string = '{"name":"Nikhil", "age":37, gender:"Male"}';

echo "Decoding: " . $string;
json_decode($string);
echo "<br>Error: ";

switch (json_last_error()) {
  case JSON_ERROR_NONE:
    echo "No errors";
    break;
  case JSON_ERROR_DEPTH:
    echo "Maximum stack depth exceeded";
    break;
  case JSON_ERROR_STATE_MISMATCH:
    echo "Invalid or malformed JSON";
    break;
  case JSON_ERROR_CTRL_CHAR:
    echo "Control character error";
    break;
  case JSON_ERROR_SYNTAX:
    echo "Syntax error";
    break;
  case JSON_ERROR_UTF8:
    echo "Malformed UTF-8 characters";
    break;
  default:
    echo "Unknown error";
    break;
}
?>

See the output below

Decoding: {"name":"Nikhil", "age":37, gender:"Male"}
Error: Syntax error