The JSON format
JSON is a text format for exchanging data. Servers answer in it, programs keep their settings in it, and a website and an app talk to each other in it. PHP can turn arrays into JSON and back.
An array to JSON
json_encode() turns a value into a JSON string:
<?php
echo json_encode(['name' => 'Anna', 'age' => 25]);An associative array becomes an object in curly braces, and a plain list becomes an array in square brackets.
Non-ASCII text and readable output
By default non-ASCII letters are replaced with codes such as А. The JSON_UNESCAPED_UNICODE flag keeps them as they are, and JSON_PRETTY_PRINT adds indentation:
<?php
$user = ['name' => 'Анна', 'tags' => ['php', 'js']];
echo json_encode($user, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);Flags are combined with a vertical bar.
JSON to an array
json_decode() does the reverse. A second argument of true means "return an associative array":
<?php
$json = '{"name": "Anna", "age": 25}';
$user = json_decode($json, true);
echo $user['name']; // AnnaParse errors
If the string is not valid JSON, json_decode() silently returns null. With the JSON_THROW_ON_ERROR flag the function throws an exception instead:
<?php
try {
json_decode('{this is not JSON}', true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo 'Could not parse the data';
}The number 512 is the allowed nesting depth; it is the default, and you have to state it to reach the fourth argument.
Storing data in a file
JSON pairs well with files: turn an array into a string and write it, then turn it back when reading:
<?php
$file = sys_get_temp_dir() . '/settings.json';
file_put_contents($file, json_encode(['theme' => 'dark', 'fontSize' => 16]));
$settings = json_decode(file_get_contents($file), true);
echo $settings['theme']; // darkA common mistake
Without the second argument true, json_decode() returns an object rather than an array. Accessing it with square brackets — $user['name'] — throws an error. Either pass true or read properties with the arrow: $user->name.