Skip to content
Tutorials Center
My learning

Topics

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.

PHP
echo json_encode(["name" => "Ada", "tags" => ["math", "code"]]);
// {"name":"Ada","tags":["math","code"]}

Try it

PHP Arrays, objects and flags

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.

PHP Objects, JsonSerializable, enums and errors

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

PHP
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 as false and become the string "" when echoed.
  • List or object? An array is a JSON array only when its keys are exactly 0..n-1 in order, which array_is_list() tests. After unset($a[1]) or array_filter() keys have gaps, so you get an object; use array_values() to re-index.
  • Empty array is always []. To get {} encode new stdClass() or use JSON_FORCE_OBJECT (which affects every nested list too).
  • Only public properties of plain objects are encoded. For a different shape, implement JsonSerializable and 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, so 0.1 + 0.2 becomes 0.30000000000000004.
  • Escaping is on by default for /, non-ASCII characters and, with JSON_HEX_*, for <, >, & and quotes. Add JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES for readable output; when printing JSON inside an HTML <script> tag also use the JSON_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").