JSON is a data interchange format contains name-value pairs. To process JSON, PHP has following in-built functions.
- json_encode()
- json_decode()
json_encode()
This json_encode functions converts data into JSON format.
Syntax
json_encode(value,flags, depth)
value | value to be encoded into JSON |
flags | optional parameter, JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_NUMERIC_CHECK, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_LINE_TERMINATORS, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_THROW_ON_ERROR. |
depth | Optional, Should not be zero. |
Example
<?php
$details = array(
'name' => 'Vasu',
'mode' => 'online',
'programming' => 'PHP'
);
// Encode the array into a JSON string
$json = json_encode($details);
// Output JSON string
echo $json;
?>
json_decode()
Converts or decodes JSON data into PHP object.
Syntax
json_decode(string, assoc, depth, options);
string | JSON string to be decoded. |
Assoc | Optional parameter, If set to true, it returns an associative array, if false, returns php object. |
depth | Optional parameter, Max Nesting depth is 512. |
options | Optional parameter, Bitmask JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR |
Example
<?php
$jsn = '{"name":"Vasu","mode":"online","programming":"PHP"}';
$php_obj = json_decode($jsn);
var_dump($php_obj);
?>