W3docs

PHP JSON

Learn how to work with JSON in PHP: encode arrays and objects with json_encode, decode strings with json_decode, format output, and handle errors safely.

JSON (JavaScript Object Notation) is a lightweight, text-based data-interchange format. It is the most common way to send and receive data between a PHP backend and a browser, a mobile app, or another web service (most REST APIs speak JSON). This guide covers everything you need to work with JSON in PHP: turning PHP data into JSON with json_encode, turning JSON back into PHP data with json_decode, formatting the output, and handling errors safely.

PHP ships JSON support in its core (the ext-json extension is bundled and enabled by default since PHP 8.0), so there is nothing to install.

What JSON looks like

JSON represents data as key-value pairs inside objects ({ }) and ordered lists inside arrays ([ ]). Values can be strings, numbers, booleans, null, arrays, or nested objects:

{
  "name": "John",
  "age": 30,
  "active": true,
  "roles": ["admin", "editor"]
}

The two functions you will use almost every time are:

  • json_encode($value) — PHP value → JSON string (serialize).
  • json_decode($json) — JSON string → PHP value (deserialize).

Encoding: PHP to JSON with json_encode

json_encode() converts a PHP value — typically an array or object — into a JSON string.

Encoding an associative array

php— editable, runs on the server

An associative array becomes a JSON object, while an indexed array (sequential integer keys starting at 0) becomes a JSON array:

<?php

echo json_encode(["red", "green", "blue"]);
// ["red","green","blue"]

?>

Formatting the output

By default json_encode produces compact JSON on a single line, which is ideal for sending over the network. When you want human-readable output (for logging or debugging), pass the JSON_PRETTY_PRINT flag. Flags are combined with the bitwise | operator:

<?php

$data = [
    "user" => ["name" => "Jane", "roles" => ["admin", "editor"]],
    "active" => true,
];

echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

?>

This prints nicely indented JSON:

{
    "user": {
        "name": "Jane",
        "roles": [
            "admin",
            "editor"
        ]
    },
    "active": true
}

Other useful flags: JSON_UNESCAPED_SLASHES (keeps / instead of \/) and JSON_UNESCAPED_UNICODE (keeps characters like é instead of é).

Decoding: JSON to PHP with json_decode

json_decode() converts a JSON string back into a PHP value. By default it returns objects, but passing true as the second argument returns associative arrays instead — which are usually easier to loop over:

php— editable, runs on the server

Without the true argument, you get a stdClass object and access values with the -> arrow notation instead of [ ]:

php— editable, runs on the server

Use true when you want an array; omit it when you prefer object syntax. Both contain the same data.

Encoding a custom object

json_encode also works on objects. When you need to build a JSON structure on the fly, the empty stdClass object lets you attach properties dynamically. (For full classes, see PHP Classes and Objects.)

php— editable, runs on the server

Public properties of any object are included automatically; private and protected properties are skipped unless the class implements the JsonSerializable interface.

Handling errors

JSON parsing can fail — a malformed string, an unterminated quote, or a trailing comma will all break decoding. When json_decode fails it returns null, so you must distinguish a real null value from an error. Check json_last_error() (or read json_last_error_msg() for a human-readable message):

<?php

$badJson = '{invalid}';
$result = json_decode($badJson);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON error: " . json_last_error_msg();
    // JSON error: Syntax error
}

?>

Since PHP 7.3 you can instead pass the JSON_THROW_ON_ERROR flag to make both functions throw a JsonException, which fits cleanly into try/catch blocks:

<?php

try {
    $data = json_decode('{invalid}', true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo "Could not parse JSON: " . $e->getMessage();
}

?>

Note: json_decode has a depth limit (512 levels by default, the third argument). Very deeply nested JSON will fail with a JSON_ERROR_DEPTH error unless you raise it.

Common use case: reading a JSON request body

When a client sends JSON to a PHP endpoint (as most APIs do), the body arrives as raw input rather than $_POST. Read it with php://input and decode it:

<?php

$body = file_get_contents("php://input");
$data = json_decode($body, true);

// echo a JSON response back to the client
header("Content-Type: application/json");
echo json_encode(["received" => $data]);

?>

Conclusion

JSON is the standard format for exchanging data in modern web applications, and PHP makes it straightforward to work with:

  • Use json_encode to turn arrays and objects into JSON; add JSON_PRETTY_PRINT for readable output.
  • Use json_decode to turn JSON back into PHP — pass true for an array, omit it for an object.
  • Always check for errors with json_last_error() or JSON_THROW_ON_ERROR before trusting decoded data.

With these tools you can confidently send and receive JSON between your PHP code, databases, browsers, and external web services.

Practice

Practice
What functions does PHP provide for handling JSON data?
What functions does PHP provide for handling JSON data?
Was this page helpful?