JSON is a data interchange format contains name-value pairs. To process JSON, PHP has following in-built functions.

  1. json_encode()
  2. json_decode()

json_encode()

This json_encode functions converts data into JSON format.

Syntax

json_encode(value,flags, depth)
valuevalue to be encoded into JSON
flagsoptional 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.
depthOptional, 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);
stringJSON string to be decoded.
AssocOptional parameter, If set to true, it returns an associative array, if false, returns php object.
depthOptional parameter, Max Nesting depth is 512.
optionsOptional 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);
?>