PHP json_encode() Function

Convert a PHP value to a JSON string

Try json_encode() - edit and run
Output
{"name":"John","age":30,"skills":["PHP","SQL"]}
[1,2,3]
{"1":"a","2":"b"}

What does json_encode() do?

json_encode() converts PHP arrays, objects, strings, numbers, booleans and null into a JSON string. Sequential arrays (keys 0, 1, 2 ...) become JSON arrays; any other array becomes a JSON object.

Syntax

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

Parameters

  • $value - The value to encode. Strings must be valid UTF-8.
  • $flags - Bitmask of options, e.g. JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_PRESERVE_ZERO_FRACTION, JSON_THROW_ON_ERROR, JSON_INVALID_UTF8_SUBSTITUTE.
  • $depth - Maximum nesting depth (must be greater than 0).

Return value

A JSON string, or false on failure (unless JSON_THROW_ON_ERROR is used, in which case a JsonException is thrown).

json_encode() examples

Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.

1. Arrays to JSON

<?php
$data = ["name" => "John", "age" => 30, "skills" => ["PHP", "SQL"]];
echo json_encode($data) . "\n";
echo json_encode([1, 2, 3]) . "\n";
echo json_encode([1 => "a", 2 => "b"]) . "\n";

Output:

{"name":"John","age":30,"skills":["PHP","SQL"]}
[1,2,3]
{"1":"a","2":"b"}

2. Useful flags: Unicode, slashes, floats, pretty print

<?php
$data = ["city" => "Zürich", "url" => "https://example.com/a/b", "price" => 10.0];
echo json_encode($data) . "\n";
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION) . "\n";
echo json_encode(["a" => 1, "b" => [1, 2]], JSON_PRETTY_PRINT) . "\n";

Output:

{"city":"Z\u00fcrich","url":"https:\/\/example.com\/a\/b","price":10}
{"city":"Zürich","url":"https://example.com/a/b","price":10.0}
{
    "a": 1,
    "b": [
        1,
        2
    ]
}

3. Why json_encode() returns false

The most common cause is a string that is not valid UTF-8 (for example data read from a Latin-1 database).

<?php
$bad = ["text" => "\xB1\x31"]; // invalid UTF-8
var_dump(json_encode($bad));
echo json_last_error_msg() . "\n";

echo json_encode($bad, JSON_INVALID_UTF8_SUBSTITUTE) . "\n";

try {
    json_encode($bad, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo "Caught: " . $e->getMessage() . "\n";
}

Output:

bool(false)
Malformed UTF-8 characters, possibly incorrectly encoded
{"text":"\ufffd1"}
Caught: Malformed UTF-8 characters, possibly incorrectly encoded

4. Objects and JsonSerializable

<?php
class User implements JsonSerializable {
    public function __construct(private string $name, private string $password) {}

    public function jsonSerialize(): array {
        return ["name" => $this->name]; // never expose the password
    }
}
echo json_encode(new User("alice", "secret")) . "\n";
echo json_encode([]) . " " . json_encode(new stdClass()) . "\n";

Output:

{"name":"alice"}
[] {}

Common mistakes and gotchas

  • Returns false silently: always check the result or use JSON_THROW_ON_ERROR. Invalid UTF-8, INF/NAN and recursion deeper than $depth are typical causes.
  • Arrays vs objects: after array_filter() or unset() an array may have gaps and encode as an object; use array_values() first. Use JSON_FORCE_OBJECT to always get objects.
  • Private properties: only public properties are encoded unless the class implements JsonSerializable.
  • Escaped slashes: "/" is escaped as "\/" by default; that is valid JSON, but JSON_UNESCAPED_SLASHES makes URLs readable.

PHP json_encode() FAQ

Why does json_encode() return false?

Usually because a string is not valid UTF-8. Call json_last_error_msg() to see the reason, fix the encoding (e.g. mb_convert_encoding()), or use JSON_INVALID_UTF8_SUBSTITUTE.

How do I pretty print JSON in PHP?

Pass JSON_PRETTY_PRINT: json_encode($data, JSON_PRETTY_PRINT). Combine with JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE for readable output.

How do I send JSON from PHP as an API response?

Send the header first and echo the encoded data: header("Content-Type: application/json"); echo json_encode($data, JSON_THROW_ON_ERROR);