PHP Reference ยท Functions and Classes
PHP json_encode() function
Reference for PHP json_encode(): turn arrays, objects and enums into JSON, pretty-print, control Unicode and slashes, JsonSerializable and error handling.
json_encode() converts a PHP value into a JSON string. Arrays with sequential keys 0, 1, 2... become JSON arrays, other arrays become JSON objects, and objects become JSON objects built from their public properties.
The function returns false on failure unless you pass JSON_THROW_ON_ERROR, which is the recommended way to call it. Flags control the look of the output (pretty printing, escaping of Unicode and slashes) and a few type conversions.
echo json_encode(["name" => "Ada", "tags" => ["math", "code"]]); // {"name":"Ada","tags":["math","code"]}
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false
| Name | Description |
|---|---|
$value |
Any type except a resource. Strings must be valid UTF-8. |
$flags |
A bitmask of JSON_* constants (see below and JSON errors and flags). |
$depth |
Maximum nesting depth. Exceeding it is an error. |
Common flags: JSON_PRETTY_PRINT (indent with four spaces), JSON_UNESCAPED_UNICODE (keep รฉ as is instead of รฉ), JSON_UNESCAPED_SLASHES (keep /), JSON_PRESERVE_ZERO_FRACTION (10.0 stays 10.0), JSON_NUMERIC_CHECK (numeric strings become numbers), JSON_FORCE_OBJECT (lists become objects), JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT (safe embedding in HTML), JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_INVALID_UTF8_SUBSTITUTE, JSON_INVALID_UTF8_IGNORE and JSON_THROW_ON_ERROR.
Return value: the JSON string, or false on failure. The reason is available from json_last_error() and json_last_error_msg().
Errors: with JSON_THROW_ON_ERROR a JsonException is thrown and the global error state is left untouched. Failure causes include invalid UTF-8, NAN and INF, too deep nesting, recursive structures, unsupported types and pure (non-backed) enums.
Usage notes
- Always pass
JSON_THROW_ON_ERROR(PHP 7.3+) so a failure cannot slip through asfalseand become the string""when echoed. - List or object? An array is a JSON array only when its keys are exactly
0..n-1in order, whicharray_is_list()tests. Afterunset($a[1])orarray_filter()keys have gaps, so you get an object; usearray_values()to re-index. - Empty array is always
[]. To get{}encodenew stdClass()or useJSON_FORCE_OBJECT(which affects every nested list too). - Only public properties of plain objects are encoded. For a different shape, implement
JsonSerializableand return an array. - Enums: backed enums encode as their value; a pure enum cannot be encoded and fails.
- Floats use
serialize_precision(-1 by default), the shortest text that reads back exactly, so0.1 + 0.2becomes0.30000000000000004. - Escaping is on by default for
/, non-ASCII characters and, withJSON_HEX_*, for<,>,&and quotes. AddJSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHESfor readable output; when printing JSON inside an HTML<script>tag also use theJSON_HEX_*flags. - Binary data and invalid UTF-8 cannot be encoded. Convert with
base64_encode()or use the substitute/ignore flags to repair text. - Large integers beyond what JavaScript can hold exactly (above 2^53) should be sent as strings to JavaScript clients.
- Sending JSON from a web script also needs
header("Content-Type: application/json").