PHP allows us to encode and decode JSON by the help of json_encode() and json_decode functions.
Function | Libraries |
---|---|
json_encode | Returns the JSON representation of a value. |
json_decode | Decodes a JSON string. |
json_last_error | Returns the last error occurred. |
The json_encode() function returns the JSON representation of a value. In other words, it converts PHP variable (containing array) into JSON.
The json_decode() function decodes the JSON string. In other words, it converts JSON string into a PHP variable.
Syntax :-
json_string − It is an encoded string which must be UTF-8 encoded data.
assoc − It is a boolean type parameter, when set to TRUE, returned objects will be converted into associative arrays.
depth − It is an integer type parameter which specifies recursion depth
options − It is an integer type bitmask of JSON decode, JSON_BIGINT_AS_STRING is supported.
Output:
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
Output:
array(3) {
["firstName"]=> string(5) "Rahul"
["lastName"]=> string(5) "Kumar"
["email"]=> string(15) "rahul@gmail.com"
}