W3docs

PHP JSON Functions Reference

A reference to PHP's built-in JSON functions — json_encode, json_decode, json_last_error, and the JSON option constants — with working examples.

JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format. Because it is easy for humans to read and trivial for machines to parse, it has become the default way to send data between a server and a browser, and between web services (REST APIs).

PHP ships with a small set of built-in functions — collectively the JSON extension — that convert PHP values to JSON text and back. This page is a quick reference to those functions and the most useful option constants. For a step-by-step tutorial, see PHP JSON.

When would I use JSON in PHP?

You reach for these functions whenever data has to leave PHP as text or arrive as text:

  • Returning data from an API endpoint (echo json_encode($data);).
  • Reading a request body or a config file written in JSON.
  • Storing a structured value (an array of settings, for example) in a single database column or cache key.
  • Talking to a third-party web service that speaks JSON.

The JSON extension is enabled by default in PHP 5.2 and later, and is part of core in PHP 8.0+, so no installation is needed.

JSON functions

FunctionDescription
json_encode()Convert a PHP value (array, object, scalar) into a JSON string.
json_decode()Convert a JSON string into a PHP value.
json_last_error()Return an integer error code from the last json_encode()/json_decode() call.
json_last_error_msg()Return a human-readable message for the last error.

json_encode()

json_encode() serializes a PHP value into a JSON-formatted string.

<?php

$data = [
    "name"  => "Ada",
    "age"   => 36,
    "langs" => ["PHP", "JS"],
];

echo json_encode($data);

?>

Output:

{"name":"Ada","age":36,"langs":["PHP","JS"]}

Note how an associative array becomes a JSON object {}, while a list-style array (["PHP","JS"]) becomes a JSON array []. See the full reference in json_encode().

Pretty-printing the output

Pass the JSON_PRETTY_PRINT option to make the result readable:

<?php

$data = ["name" => "Ada", "langs" => ["PHP", "JS"]];

echo json_encode($data, JSON_PRETTY_PRINT);

?>

Output:

{
    "name": "Ada",
    "langs": [
        "PHP",
        "JS"
    ]
}

json_decode()

json_decode() parses a JSON string and turns it into a PHP value. By default it returns objects (stdClass); pass true as the second argument to get associative arrays instead.

<?php

$json = '{"name":"Ada","age":36,"langs":["PHP","JS"]}';

// Decode as an associative array
$data = json_decode($json, true);

echo $data["name"];   // Ada
echo "\n";
echo $data["langs"][0]; // PHP

?>

Output:

Ada
PHP

See the full reference in json_decode().

Handling errors

json_encode() returns false and json_decode() returns null when something goes wrong (invalid UTF-8, a syntax error in the input, or nesting deeper than the depth limit). Because null is also a valid decoded value, always check json_last_error() rather than only testing for null.

<?php

$bad = '{"name": "Ada", }';   // trailing comma is invalid JSON

$result = json_decode($bad, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo "Invalid JSON: " . json_last_error_msg();
} else {
    echo "Decoded fine.";
}

?>

Output:

Invalid JSON: Syntax error

In PHP 7.3+ you can pass the JSON_THROW_ON_ERROR flag to both functions to get a JsonException instead of inspecting the error code manually.

Common option constants

These bitmask constants are passed in the $options argument of json_encode() (and some apply to json_decode()):

  • JSON_PRETTY_PRINT — format the output with whitespace and indentation.
  • JSON_UNESCAPED_SLASHES — leave / characters un-escaped (http:// instead of http:\/\/).
  • JSON_UNESCAPED_UNICODE — keep multibyte characters as-is instead of \uXXXX escapes.
  • JSON_THROW_ON_ERROR — throw a JsonException on failure (PHP 7.3+).
  • JSON_FORCE_OBJECT — always emit a JSON object, even for a sequential array.

Combine them with the bitwise OR operator:

<?php

$data = ["site" => "https://www.w3docs.com", "name" => "café"];

echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

?>

Output:

{
    "site": "https://www.w3docs.com",
    "name": "café"
}

Practice

Practice
What are the json_encode and json_decode functions in PHP used for?
What are the json_encode and json_decode functions in PHP used for?
Was this page helpful?