JSON
suggest changeVersions
The original topic was tagged for PHP 5.2 through 7.1. The JSON extension has shipped with PHP since 5.2.
Introduction
JSON (JavaScript Object Notation) is a language-independent text format for structured data. PHP's JSON extension encodes and decodes it.
Syntax
- string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
- mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
Parameters
| Parameter | Details |
|---|---|
| json_encode | |
| value | The value being encoded. Can be any type except a resource. All string data must be UTF-8 encoded. |
| options | Bitmask of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR. Later PHP versions add more flags, including JSON_THROW_ON_ERROR (PHP 7.3). See the JSON constants page. |
| depth | Maximum depth. Must be greater than zero. |
| json_decode | |
| json | The JSON string being decoded. The function only accepts UTF-8. |
| assoc | When true, return associative arrays instead of objects. |
| options | Bitmask of decode options. The original list was only JSON_BIGINT_AS_STRING (by default, integers too large for PHP become floats). Later flags also exist. |
Remarks
json_decode returns null both for invalid JSON and for the JSON value null. Call json_last_error() after each decode, or pass JSON_THROW_ON_ERROR (PHP 7.3 and later) so failure throws JsonException.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents