May 08, 2021 JSON
This tutorial will teach us how to encode and decode JSON objects using the PHP programming language. Let's prepare the environment for PHP programming for JSON.
The JSON extension is bundled by default and compiled into PHP starting with PHP 5.2.0.
Function | The library |
---|---|
json_encode | Returns a JSON representation of a value. |
json_decode | Decoded as a JSON string. |
json_last_error | Returns the last error that happened. |
PhP's json_encode() function is used to encode JSON in PHP. When encoding is successful, the function returns the JSON representation of a given value, and if it fails, false.
Grammar:
string json_encode ( $value [, $options = 0 ] )
Parameters:
Example:
The following example shows how to convert an array to JSON using PHP:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
The execution produces the following results:
{"a":1,"b":2,"c":3,"d":4,"e":5}
The following example shows that PHP objects can also be converted to JSON:
<?php
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', strtotime("8/5/1974 12:20:03"));
echo json_encode($e);
?>
The execution produces results such as the following:
{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}
The json-decode() function of PHP is used to decode JSON in PHP. This function returns a value from JSON decoding to the appropriate PHP type.
Grammar:
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
Parameters:
Example:
The following example shows how to decode a JSON object using PHP:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
The results are generated on execution as follows:
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)
}