The best PHP JSON Tutorial In 2024, In this tutorial you can learn Environment Configuration,JSON Functions,json_encode,json_decode,
This chapter we will introduce how to use the PHP language to encode and decode JSON objects.
In php5.2.0 and above has built JSON extension.
function | description |
---|---|
json_encode | The variables are encoded in JSON |
json_decode | String JSON format decoding, converted to PHP variables |
json_last_error | Returns last error occurred |
PHP json_encode () for JSON-encoded variables, the function returns JSON data if executed successfully, otherwise it returns FALSE.
string json_encode ( $value [, $options = 0 ] )
The following example demonstrates how PHP array into JSON formatted data:
<?php $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr); ?>
The above code is executed as a result of:
{"a":1,"b":2,"c":3,"d":4,"e":5}
The following example demonstrates how PHP object into a JSON formatted data:
<?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', "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); ?>
The above code is executed as a result of:
{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}
PHP json_decode () function is used to format JSON string is decoded and converted to PHP variables.
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
json_string: to be decoded JSON strings must be UTF-8 encoded data
assoc: When this parameter is TRUE, it returns an array, returns the object FALSE.
depth: an integer value that specifies the recursion depth
options: a binary mask, currently only supports JSON_BIGINT_AS_STRING.
The following example demonstrates how to decode JSON data:
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); var_dump(json_decode($json, true)); ?>
The above code is executed as a result of:
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) }