json_encode
Converts a PHP value into its JSON string representation.
json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false- Added in PHP 5.2.0
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to encode. Any type except a resource; all strings inside it must be valid UTF-8. |
$flagsoptional | int= 0 | Bitmask of JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_FORCE_OBJECT, JSON_NUMERIC_CHECK, JSON_PRESERVE_ZERO_FRACTION, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_THROW_ON_ERROR, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT and JSON_UNESCAPED_LINE_TERMINATORS. |
$depthoptional | int= 512 | Maximum recursion depth of the value being encoded. Must be greater than zero. |
Return value
string|falseA JSON encoded string on success, or false on failure.
Errors
Throws JsonException when JSON_THROW_ON_ERROR is set and the value cannot be encoded, and ValueError when depth is not greater than zero.
Changelog
- PHP 7.3.0JSON_THROW_ON_ERROR was added, so encoding failures can raise a JsonException instead of returning false.
- PHP 7.2.0JSON_INVALID_UTF8_IGNORE and JSON_INVALID_UTF8_SUBSTITUTE were added, giving a way to encode data with broken UTF-8 instead of failing.
- PHP 7.1.0Floats are formatted with the serialize_precision ini setting instead of precision, which changed the digits emitted for many float values.
- PHP 7.1.0JSON_UNESCAPED_LINE_TERMINATORS was added for output embedded in JavaScript.
JSON_UNESCAPED_SLASHES and JSON_UNESCAPED_UNICODE to stop URLs turning into http:\/\/ and accented characters into é.Example
When to use it
- Return an API response body from a controller alongside a Content-Type: application/json header.
- Store a structured settings blob in a single database text or JSON column.
- Pass server-side data into a JavaScript variable in a template.
- Write a fixture or cache file that a human might have to open and read.
Frequently asked questions
Why does json_encode return false?
The most common causes are a string somewhere in the value that is not valid UTF-8, an INF or NAN float, a resource, or a recursive reference between objects. Call json_last_error_msg() straight afterwards to see which, or pass JSON_THROW_ON_ERROR to get an exception with the reason.
Why does json_encode escape forward slashes and accented characters?
That is the default so the output is safe to embed directly inside a <script> tag and in pure ASCII transports. Pass JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE to get / and é literally; both forms decode to exactly the same value.
Why does my array encode as an object instead of an array?
json_encode emits a JSON array only when the PHP array keys are the integers 0 to n-1 in order. Any string key, gap, or reordering makes it a JSON object, so call array_values() on lists before encoding them.
More examples
Lists, gaps and forced objects
The first line prints ["a","b","c"]. After unset the keys are 0 and 2, so the same array now encodes as the object {"0":"a","2":"c"} and any JavaScript client expecting an array breaks. array_values() re-indexes and restores ["a","c"]. An empty array is ambiguous: it encodes as [] unless you force {}.
<?php
$list = ['a', 'b', 'c'];
echo json_encode($list), "\n";
unset($list[1]);
echo json_encode($list), "\n";
echo json_encode(array_values($list)), "\n";
echo json_encode([]), "\n";
echo json_encode([], JSON_FORCE_OBJECT), "\n";Controlling object output with JsonSerializable
Without JsonSerializable, json_encode only exports public properties, so private $cents and $currency would vanish and produce {}. Implementing jsonSerialize() lets the class decide its own wire shape, printing {"total":{"amount":19.99,"currency":"EUR"}}. A plain stdClass with no properties encodes as {}.
<?php
class Money implements JsonSerializable {
public function __construct(
private int $cents,
private string $currency,
) {}
public function jsonSerialize(): array {
return ['amount' => $this->cents / 100, 'currency' => $this->currency];
}
}
echo json_encode(['total' => new Money(1999, 'EUR')]), "\n";
echo json_encode(new stdClass()), "\n";Handling values that cannot be encoded
The stray 0xE9 byte is not valid UTF-8, so the first call returns false and json_last_error_msg() reports "Malformed UTF-8 characters". JSON_INVALID_UTF8_SUBSTITUTE replaces the bad byte with U+FFFD and produces usable output. INF and NAN are not representable in JSON at all, and with JSON_THROW_ON_ERROR that becomes a JsonException instead of a silent false.
<?php
$broken = ['label' => "caf\xE9"]; // latin-1 byte, not UTF-8
var_dump(json_encode($broken));
echo json_last_error_msg(), "\n";
echo json_encode($broken, JSON_INVALID_UTF8_SUBSTITUTE), "\n";
try {
json_encode(['n' => INF], JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo 'Caught: ', $e->getMessage(), "\n";
}
Discussion