In PHP, json_encode() converts a PHP value, such as an array or object, into a JSON string. It is the opposite of json_decode().
You use json_encode() when you want to send data to JavaScript, save it in a file, or return it from an API. Associative arrays and objects become JSON objects, and lists become JSON arrays. It returns false if encoding fails, or throws a JsonException with JSON_THROW_ON_ERROR.
Syntax
Call json_encode() with the values you need. Start with this line.
Returns readable, indented JSON and throws a JsonException if encoding fails.
Combine several flags with the | operator. Use JSON_PRETTY_PRINT to make output easy to read, JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_SLASHES to keep characters as they are, and JSON_THROW_ON_ERROR to handle failures with exceptions.
Library declarations
PHP
json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false
Parameters
Parameter
Description
value
Required. The value to encode. It can be any type except a resource. Strings must be valid UTF-8.
flags
Optional. A bitmask of options such as JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE, JSON_UNESCAPED_SLASHES, JSON_THROW_ON_ERROR, JSON_FORCE_OBJECT and JSON_NUMERIC_CHECK. The default is 0.
depth
Optional. The maximum nesting depth. The default is 512. It must be greater than 0, and encoding fails if the value is nested deeper than this.
Return Value
Return Value
Description
string
The JSON representation of the value.
false
Returned when encoding fails, for example with invalid UTF-8 text, NAN or INF, a resource, or a depth error. With JSON_THROW_ON_ERROR a JsonException is thrown instead.
PHP Examples
Example 1 — Arrays Become Objects or Lists
An associative array becomes a JSON object, while a plain list becomes a JSON array.
The data is nested three levels deep: a, then b, then c.
A depth limit of 2 is too small, so PHP throws a JsonException because of JSON_THROW_ON_ERROR.
The catch block prints the exception message.
The second call uses the default depth and JSON_PRETTY_PRINT, which indents the JSON with four spaces.
Frequently Asked Questions
It converts a PHP value such as an array, object, string or number into a JSON string. It is often used to send data to JavaScript or to build API responses.
Pass JSON_PRETTY_PRINT as the second argument. PHP then adds line breaks and four-space indentation, which is great for debugging and for files people will read.
Common reasons are text that is not valid UTF-8, values like NAN or INF, resources that cannot be encoded, or data nested deeper than the depth limit. Use JSON_THROW_ON_ERROR to get a clear exception instead of false.
An empty PHP array has no keys, so PHP treats it as a list and writes []. If you need an empty JSON object, use new stdClass() or pass the JSON_FORCE_OBJECT flag.
Combine JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_SLASHES with the | operator. Without them PHP writes characters like é as \u00e9 and slashes as \/.