json_encode()
json_encode() — Returns the JSON representation of a value.
Built-in function of PHP 8.5. The manual lists it as available in PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
Returns a string containing the JSON representation of the supplied value. If the parameter is an array or object, it will be serialized recursively.
Signature
json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $value | mixed | The value being encoded. Can be any type except a resource. |
| $flags | int | Bitmask 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. The behaviour of these constants is described on the JSON ... |
| $depth | int | Set the maximum depth. Must be greater than zero. |
Return value
Returns a JSON encoded string on success or false on failure.
Example
A runnable snippet:
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr);
Output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Changelog
| Version | Change |
|---|---|
| 7.3.0 | JSON_THROW_ON_ERROR flags was added. |
| 7.2.0 | JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE flags were added. |
| 7.1.0 | JSON_UNESCAPED_LINE_TERMINATORS flags was added. |
| 7.1.0 | serialize_precision is used instead of precision when encoding float values. |
See also
json_decode(), json_last_error(), json_last_error_msg(), serialize()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page json_encode() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.