Call json_encode($array). A list such as ['a', 'b'] becomes a JSON array and an array with string keys becomes a JSON object. Add JSON_PRETTY_PRINT for indented output and JSON_THROW_ON_ERROR so a failure throws instead of returning false. To return JSON from a web script, send header('Content-Type: application/json'); before you echo json_encode($data);.
PHP has one function for this, json_encode, bundled since 5.2 and always available since PHP 8.0. The questions start after the first call: why an array came out as {"0":10,"2":20} instead of a list, how to get {} rather than [], why the slashes in a URL are escaped, why the result is false, what happens to objects and floats, and how to send the result to a browser. The sections below answer each one, then a table sums up the flags. Each example runs on this page: hit Run, then edit the code and run it again.
1json_encode: lists and associative arraysRecommended
JSON has two containers, arrays and objects, and PHP has only arrays, so json_encode picks one by looking at the keys. If they are exactly 0, 1, 2, … in order (a list, what array_is_list checks since PHP 8.1), you get a JSON array. Any other keys, including a list with a gap, give a JSON object. Strings, ints, floats, true, false and null map to their JSON counterparts, and nested arrays are encoded the same way at every level.
<?php // A list (keys 0, 1, 2...) becomes a JSON array $tags = ['php', 'json', 'api']; echo json_encode($tags), "\n"; // String keys make a JSON object $user = ['id' => 7, 'name' => 'Ada', 'admin' => false, 'email' => null]; echo json_encode($user), "\n"; // Nesting works to any depth echo json_encode(['ok' => true, 'user' => $user, 'tags' => $tags]), "\n"; // A list with a gap is no longer a list, so it becomes an object $even = array_filter([10, 15, 20, 25], fn(int $n): bool => $n % 2 === 0); var_dump(array_is_list($even)); echo json_encode($even), "\n"; echo json_encode(array_values($even)), "\n"; // An empty array is always [] echo json_encode(['settings' => []]), "\n"; // For an empty object use (object) [] or new stdClass() echo json_encode(['settings' => (object) []]), "\n"; echo json_encode(['settings' => new stdClass()]), "\n"; // JSON_FORCE_OBJECT makes every array an object echo json_encode([], JSON_FORCE_OBJECT), "\n"; echo json_encode(['a', 'b'], JSON_FORCE_OBJECT), "\n";
Output
The list prints as ["php","json","api"] and the array with string keys as an object, with false and null carried over as JSON literals. array_filter kept the keys 0 and 2, so array_is_list says bool(false) and the result is {"0":10,"2":20}, an object a JavaScript client can't .map() over; array_values renumbers it to [10,20]. An empty array prints as [], while (object) [] and new stdClass() both give {}. JSON_FORCE_OBJECT gives {} too, but it applies to the whole value, so the list ['a', 'b'] turns into {"0":"a","1":"b"}.
2Pretty-printing: JSON_PRETTY_PRINT and friends
The second argument of json_encode takes flags, combined with |. JSON_PRETTY_PRINT puts each value on its own line with a 4-space indent. Two more are worth adding almost every time: JSON_UNESCAPED_SLASHES stops / from turning into \/, and JSON_UNESCAPED_UNICODE writes characters such as é as UTF-8 instead of \u00e9 escapes. Both outputs are valid JSON and decode to the same data; the flags only change how it reads.
<?php
$menu = [
'title' => 'Café menu',
'url' => 'https://example.com/menu/today',
'items' => [
['name' => 'Crème brûlée', 'price' => 6.5],
['name' => 'Espresso', 'price' => 2],
],
];
// Default: one line, slashes and non-ASCII characters escaped
echo json_encode($menu), "\n\n";
// Indented, with readable slashes and UTF-8
echo json_encode(
$menu,
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
), "\n\n";
// The indent is always 4 spaces; halve it for a 2-space style
$json = json_encode($menu['items'][1], JSON_PRETTY_PRINT);
echo preg_replace_callback(
'/^ +/m',
fn(array $m): string => str_repeat(' ', intdiv(strlen($m[0]), 2)),
$json
), "\n";
Output
The default line escapes every / as \/ and é as \u00e9. With the three flags, each value sits on its own line with a 4-space indent, the URL reads as written and Crème brûlée keeps its accents. PHP has no setting for the indent width, so the last part halves each run of leading spaces to get the 2-space style. Pretty output is for people reading files and logs; for an API response the compact form is smaller, and clients parse both the same way.
3When json_encode returns false
json_encode fails on data JSON can't represent, and by default it fails quietly: it returns false, prints nothing, and leaves the reason in json_last_error_msg(). If you echo that false, the client gets an empty body. The usual cause is a string that isn't valid UTF-8, often text from a database or file in Latin-1. Pass JSON_THROW_ON_ERROR (PHP 7.3+) so the failure throws a JsonException you can't miss, or tell PHP what to do with bad bytes.
<?php // "\xE9" is the Latin-1 byte for an accented e: not valid UTF-8 $row = ['id' => 1, 'city' => "Montr\xE9al"]; // By default json_encode returns false and you have to ask why $json = json_encode($row); var_dump($json); echo json_last_error_msg(), "\n"; // JSON_THROW_ON_ERROR turns the failure into an exception try { $json = json_encode($row, JSON_THROW_ON_ERROR); } catch (JsonException $e) { echo 'JsonException: ', $e->getMessage(), "\n"; } // Or replace the bad bytes with U+FFFD, or drop them echo json_encode($row, JSON_INVALID_UTF8_SUBSTITUTE), "\n"; echo json_encode($row, JSON_INVALID_UTF8_IGNORE), "\n"; // The real fix: convert the text to UTF-8 where it comes in $row['city'] = mb_convert_encoding($row['city'], 'UTF-8', 'ISO-8859-1'); echo json_encode($row, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE), "\n"; // NAN and INF have no JSON form either try { json_encode(['ratio' => NAN], JSON_THROW_ON_ERROR); } catch (JsonException $e) { echo 'JsonException: ', $e->getMessage(), "\n"; }
Output
The plain call gives bool(false), and only json_last_error_msg() explains it: Malformed UTF-8 characters, possibly incorrectly encoded. With JSON_THROW_ON_ERROR the same message arrives as a JsonException; left uncaught, it stops the script instead of sending an empty response. Note that the flag leaves json_last_error() untouched, so read the exception, not the error functions. JSON_INVALID_UTF8_SUBSTITUTE writes Montr\ufffdal (the replacement character) and JSON_INVALID_UTF8_IGNORE writes Montral, losing the letter; converting from ISO-8859-1 with mb_convert_encoding gives the right Montréal. A NAN or INF value fails with Inf and NaN cannot be JSON encoded.
4Objects, JsonSerializable and dates
json_encode also takes objects. A plain object is encoded as a JSON object of its public properties; protected and private ones are left out, which keeps a password hash out of the response but also hides data you may want. A backed enum is encoded as its value. For full control, implement JsonSerializable: its jsonSerialize() method returns what should be encoded in place of the object, so you can rename keys, add computed fields and format dates.
<?php enum Status: string { case Active = 'active'; case Banned = 'banned'; } class User { public function __construct( public int $id, public string $name, protected string $email, private string $passwordHash, public Status $status = Status::Active, ) { } } // Only public properties go out; a backed enum becomes its value $user = new User(7, 'Ada', '[email protected]', 'secret-hash'); echo json_encode($user), "\n"; final class Order implements JsonSerializable { public function __construct( private int $id, private array $items, private DateTimeImmutable $placedAt, ) { } // Whatever this returns is encoded instead of the object public function jsonSerialize(): array { return [ 'id' => $this->id, 'items' => $this->items, 'total' => array_sum(array_column($this->items, 'price')), 'placedAt' => $this->placedAt->format(DATE_ATOM), ]; } } $placed = new DateTimeImmutable('2026-12-01 09:30:00'); $items = [['sku' => 'A1', 'price' => 5], ['sku' => 'B2', 'price' => 7]]; echo json_encode(['order' => new Order(42, $items, $placed)]), "\n"; // A date on its own encodes its internal fields echo json_encode($placed), "\n";
Output
User encodes as {"id":7,"name":"Ada","status":"active"}: the protected email and the private hash are skipped, and Status::Active becomes "active". A pure enum, one without values, can't be encoded and fails with Non-backed enums have no default serialization. Order keeps every property private, yet its jsonSerialize() result appears in full, with a computed "total":12 and the date as 2026-12-01T09:30:00+00:00. Encoding the DateTimeImmutable directly gives {"date":"2026-12-01 09:30:00.000000","timezone_type":3,"timezone":"UTC"}, PHP's internal fields, which a client would have to take apart, so format dates yourself.
5Floats, numeric strings and database rows
Numbers are where JSON output most often surprises people. Since PHP 7.1, json_encode uses serialize_precision, which defaults to -1: each float is written in the shortest form that reads back as exactly the same number. A whole float such as 10.0 loses its .0 unless you pass JSON_PRESERVE_ZERO_FRACTION. Strings stay strings even when they hold digits; JSON_NUMERIC_CHECK converts them, but it converts every one it can. The last part encodes rows from a database query, the "JSON encode MySQL results" case.
<?php // The shortest form that reads back as the same float echo json_encode([0.1 + 0.2, 1 / 3, 2.50, 1e25]), "\n"; // A whole float drops its .0 unless you ask to keep it echo json_encode(['price' => 10.0]), "\n"; echo json_encode(['price' => 10.0], JSON_PRESERVE_ZERO_FRACTION), "\n"; // Numeric strings stay strings... $form = [ 'qty' => '3', 'zip' => '02134', 'phone' => '+15551234', 'card' => '12345678901234567890', ]; echo json_encode($form), "\n"; // ...and JSON_NUMERIC_CHECK converts every one it can, even these echo json_encode($form, JSON_NUMERIC_CHECK), "\n"; // Database rows: fetch associative arrays, then encode the list $db = new PDO('sqlite::memory:'); $db->exec('CREATE TABLE products (id INTEGER, name TEXT, price REAL)'); $db->exec("INSERT INTO products VALUES (1, 'Pen', 1.5), (2, 'Book', 12.0)"); $rows = $db->query('SELECT id, name, price FROM products') ->fetchAll(PDO::FETCH_ASSOC); echo json_encode($rows, JSON_PRESERVE_ZERO_FRACTION), "\n";
Output
0.1 + 0.2 prints as 0.30000000000000004: that is the float's real value, not a json_encode bug, and JavaScript prints the same. 2.50 comes out as 2.5, 1e25 as 1.0e+25, and 10.0 as 10 unless JSON_PRESERVE_ZERO_FRACTION is set. JSON_NUMERIC_CHECK shows why it is risky: the zip code loses its leading zero (2134), the phone number loses its +, and the 20-digit card number becomes the float 1.2345678901234567e+19, a different number. Cast the fields you mean instead, such as (int) $form['qty']. The SQLite rows arrive with real ints and floats, so the list encodes cleanly. With MySQL, depending on the driver, PHP version and settings, columns can arrive as strings, so check the output and cast where needed; with mysqli, $result->fetch_all(MYSQLI_ASSOC) gives the same list of rows.
6Returning JSON from a PHP script
A script that answers a fetch() call or an API client needs three things: a Content-Type header that says the body is JSON, the encoded body, and nothing else in the output. Send the header with header('Content-Type: application/json');, set a status other than 200 with http_response_code(404); where it applies, print the body with echo json_encode($data, JSON_THROW_ON_ERROR);, and end with exit; so no template or stray output follows it. JSON is always UTF-8, so the header needs no charset.
These calls aren't a runnable example here because the examples on this page run PHP from the command line, where header() has no visible effect: there is no HTTP response to attach it to. Two things break the pattern on a real server. Any output before header(), even a blank line before <?php or a PHP warning, triggers Cannot modify header information - headers already sent and the header is lost; leaving out the closing ?> tag in PHP-only files avoids the trailing-newline version of that. And an echo of a failed json_encode sends an empty body, which is why the flag from section 3 belongs on every response. On the client, await response.json() parses the result; going the other way in PHP is covered in parsing JSON into an array.
7Which should you use?
| Method | What it does | Use it |
|---|---|---|
| json_encode($data) | Compact JSON, or false on failure | Only with a check for false |
| JSON_THROW_ON_ERROR | Throws JsonException on failure | Always (PHP 7.3+) |
| JSON_PRETTY_PRINT | Newlines and a 4-space indent | Files, logs, debugging |
| JSON_UNESCAPED_SLASHES | Writes / instead of \/ | Output with URLs or paths |
| JSON_UNESCAPED_UNICODE | Writes UTF-8 instead of \u escapes | Non-English text |
| JSON_INVALID_UTF8_SUBSTITUTE | Replaces bad bytes with U+FFFD | Text you can't clean at the source |
| (object) [] / JSON_FORCE_OBJECT | {} instead of [] | One empty object / every array |
| JSON_PRESERVE_ZERO_FRACTION | Keeps 10.0 as 10.0 | Clients that check float types |
| JSON_NUMERIC_CHECK | Turns every numeric string into a number | Rarely; cast the fields you mean |
| JsonSerializable | Your method decides the output | Objects, private data, dates |
Frequently asked questions
How do I return JSON from a PHP script?
Send the header first, then the body, then stop: header('Content-Type: application/json');, echo json_encode($data, JSON_THROW_ON_ERROR);, exit;. Nothing may be printed before header(), or PHP reports "headers already sent" and the header is dropped. Use http_response_code() to send a status such as 404 or 422 along with an error object.
How do I pretty-print JSON in PHP?
Pass JSON_PRETTY_PRINT: json_encode($data, JSON_PRETTY_PRINT) puts each value on its own line with a 4-space indent. Add JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE so URLs and accented letters stay readable. The indent width is fixed; for 2 spaces, post-process the leading spaces with preg_replace_callback('/^ +/m', ...). To pretty-print a JSON string you already have, decode it first: json_encode(json_decode($json), JSON_PRETTY_PRINT).
Why does json_encode return false?
The data holds something JSON can't represent. The most common case is a string that isn't valid UTF-8, which gives "Malformed UTF-8 characters, possibly incorrectly encoded"; NAN and INF give "Inf and NaN cannot be JSON encoded". Call json_last_error_msg() to see the reason, or pass JSON_THROW_ON_ERROR so it throws a JsonException. Fix bad text with mb_convert_encoding or the JSON_INVALID_UTF8_SUBSTITUTE flag.
Why does my array encode as an object instead of a JSON array?
Its keys are not exactly 0, 1, 2 in order. That usually happens after array_filter, unset or array_unique, which keep the original keys, so [0 => 10, 2 => 20] encodes as {"0":10,"2":20}. Wrap the array in array_values() to renumber it. array_is_list() (PHP 8.1) tells you in advance which form you will get.
How do I encode an empty array as {} instead of []?
An empty PHP array always encodes as []. For a single empty object, use (object) [] or new stdClass(), which encode as {}. The JSON_FORCE_OBJECT flag also gives {}, but it turns every array in the data into an object, lists included, so ['a', 'b'] becomes {"0":"a","1":"b"}.
Why are private properties missing from json_encode output?
json_encode only sees what is visible from outside the object, so it encodes public properties and skips protected and private ones. Implement JsonSerializable and return an array from jsonSerialize() to choose the fields yourself. A DateTimeImmutable encoded directly gives {"date":"2026-12-01 09:30:00.000000","timezone_type":3,"timezone":"UTC"}, so format dates with format(DATE_ATOM) instead.
How do I convert a JSON string back into a PHP array?
Use json_decode($json, true); the true makes JSON objects come back as associative arrays instead of stdClass objects. Add flags: JSON_THROW_ON_ERROR so invalid JSON throws rather than returning null.