W3docs

JSON encoding with PHP

Learn how to use PHP json_encode() to convert arrays and objects into JSON strings, with flags like JSON_PRETTY_PRINT, type mapping, and error handling.

JSON (JavaScript Object Notation) is a lightweight, text-based data-interchange format that is easy for humans to read and easy for machines to parse. It is the de facto format for sending data between a server and the browser, for REST APIs, and for config files. In PHP, json_encode() takes a PHP value — a scalar, an array, or an object — and returns its JSON representation as a string.

This page covers the syntax, the most useful $flags, how PHP types map to JSON, and how to detect encoding errors. To go the other way (JSON string → PHP value) see json_decode().

Syntax

json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false

It returns a JSON-encoded string on success, or false on failure (for example, when the input contains malformed UTF-8).

Parameters

  • $value — the value to encode. It can be any type except a resource. All string data must be valid UTF-8.
  • $flags (optional) — a bitmask that customizes the output. The most common ones:
    • JSON_PRETTY_PRINT — adds whitespace and indentation so the output is readable.
    • JSON_UNESCAPED_UNICODE — keeps multibyte characters (é, ñ, 日) literal instead of escaping them to \uXXXX.
    • JSON_UNESCAPED_SLASHES — leaves / unescaped (PHP escapes it as \/ by default).
    • JSON_FORCE_OBJECT — encodes a sequential array as a JSON object ({}) instead of an array ([]).
    • JSON_THROW_ON_ERROR — throws a JsonException on failure instead of returning false (PHP 7.3+).
    • Combine flags with the bitwise OR operator: JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE.
  • $depth (optional) — the maximum nesting depth. Must be greater than 0. The default of 512 is plenty for normal data.

How PHP types map to JSON

PHP valueJSON output
Sequential array ([1, 2, 3])array — [1,2,3]
Associative array / objectobject — {"key":"value"}
string"string" (must be UTF-8)
int / floatnumber — 9.5
true / falsetrue / false
nullnull

Examples

Encoding an array

A PHP associative array becomes a JSON object; the keys become property names.

php— editable, runs on the server

Output:

{"a":1,"b":2,"c":3,"d":4,"e":5}

Encoding an object

Public properties of an object are encoded; private and protected properties are skipped.

php— editable, runs on the server

Output:

{"name":"John Doe","age":35,"city":"New York"}

Pretty-printing and unescaped Unicode

By default the output is compact, on one line, and non-ASCII characters are escaped (so é becomes é). Two flags make the output human-friendly:

<?php

$data = [
    "name"  => "Café",
    "tags"  => ["php", "json"],
    "price" => 9.50,
];

echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

?>

Output:

{
    "name": "Café",
    "tags": [
        "php",
        "json"
    ],
    "price": 9.5
}

Note that 9.50 is emitted as 9.5 — trailing zeros on floats are dropped. Use JSON_PRESERVE_ZERO_FRACTION if you need 9.0 to stay a float rather than become 9.

Handling errors

If json_encode() returns false, something went wrong — most often malformed UTF-8 in a string. Check json_last_error_msg(), or pass JSON_THROW_ON_ERROR to get an exception instead.

<?php

$value = json_encode("\xB1\x31"); // invalid UTF-8 byte sequence

if ($value === false) {
    echo "Encoding failed: " . json_last_error_msg();
}

?>

Output:

Encoding failed: Malformed UTF-8 characters, possibly incorrectly encoded

Common use cases

  • Returning data from an API. Set the header and echo the encoded array:

    header('Content-Type: application/json');
    echo json_encode(['status' => 'ok', 'items' => $items]);
  • Storing structured data in a file or a database text column instead of serialize(). JSON is portable across languages; serialize() is PHP-only.

  • Passing data to JavaScript rendered on the page, since valid JSON is valid JavaScript object syntax.

Conclusion

json_encode() turns PHP arrays and objects into a compact, portable JSON string. Reach for JSON_PRETTY_PRINT and JSON_UNESCAPED_UNICODE when a human will read the output, guard against malformed input by checking the return value or using JSON_THROW_ON_ERROR, and remember that only public object properties are encoded. To parse JSON back into PHP, use json_decode(); for a broader overview, see Working with JSON in PHP.

Practice

Practice
What does the function json_encode() in PHP do?
What does the function json_encode() in PHP do?
Was this page helpful?