Syntax:
string json_encode ($value, $option, $depth)Parameters :
- $value:this is a required parameter that defines the value to be encoded.
- $option: This is an optional parameter that determines the bit mask consisting of 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:is an optional parameter that sets the maximum depth. Its value must be greater than zero.
// Declare the array
$value
=
array
(
"name"
= >
" GFG "
,
"email"
= >
"[email protected]"
) ;
// Using the json_encode() function
$json
= json_encode (
$value
);
// Show output
echo
(
$json
) ;
?>
Exit:{"name ":" GFG "," email ":" [email protected] "}
Example 2:This example encodes a PHP multidimensional array to JSON representation.
// Declare a multidimensional array
$value
=
array
(
"name"
= >
"GFG"
,
array
(
"email"
= > "[email protected]"
,
"mobile"
= >
"XXXXXXXXXX"
)
);
// Using the json_encode() function
$json
= json_encode (
$value
);
// Show output
echo
(
$json
) ;
?>
Exit:{"name ":" GFG "," 0 ": {" email ":" [email protected] "," mobile ":" XXXXXXXXXX "}}
Example 3:This the example encodes PHP objects into JSON representation.
// Declare the class
class
GFG {
}
// Declare the object
$value
=
new
GFG();
// Set object elements
$value
-> organization =
"GeeksforGeeks"
;
$value
-> email =
"[email protected]"
;
// Using the json_encode() function
$json
= json_encode (
$value
);
// Show output
echo
(
$json
) ;
?>
Exit:{"organization ":" GeeksforGeeks "," email ":" [email protected] "}
Link: https://www.php.net/manual/en/function.json-encode.php