PHP json_encode() Function
Example
How to encode an associative array into a JSON object:
<?php
$age = array("Peter"=>35, "Ben"=>37, "Joe"=>43);
echo json_encode($age);
?>
Run Example »
Definition and Usage
The json_encode() function is used to encode a value to JSON format.
Syntax
json_encode(value, options, depth)
Parameter Values
Parameter | Description |
---|---|
value | Required. Specifies the value to be encoded |
options | Optional. Specifies a bitmask (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. Specifies the maximum depth |
Technical Details
Return Value: | Returns a JSON encoded string on success. FALSE on failure |
---|---|
PHP Version: | 5.2+ |
PHP Changelog: | PHP 7.3: Added JSON_THROWN_ON_ERROR option PHP 7.2: Added JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE options PHP 7.1: Added JSON_UNESCAPED_LINE_TERMINATORS option PHP 5.6: Added JSON_PRESERVE_ZERO_FRACTION option PHP 5.5: Added depth parameter PHP 5.5: Added JSON_PARTIAL_OUTPUT_ON_ERROR option PHP 5.5: Changed return value on failure from null to FALSE PHP 5.4: Added JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE options PHP 5.3: Added JSON_FORCE_OBJECT, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT, JSON_HEX_TAG, and JSON_NUMERIC_CHECK options PHP 5.3: Added options parameter |
More Examples
Example
How to encode an indexed array into a JSON array:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo json_encode($cars);
?>
Run Example »
❮ PHP JSON Reference