If you build anything in PHP, you will meet JSON files sooner or later. Your app reads settings from a config.json, caches an API response in a file, stores a small list of records without a database, or exports data for another system to consume. JSON is the format all of these jobs share, and PHP has built-in functions for it โ but the built-in functions have sharp edges that catch almost every beginner, and a few experienced developers too.
The most common surprise is silence. When json_decode() meets broken JSON, it does not throw an error or print a warning. It quietly returns null, and your code carries on as if the file were empty. The second surprise is the half-written file: a script that crashes in the middle of file_put_contents() leaves a truncated JSON file behind, and the next request that reads it gets nothing at all. Both problems are easy to prevent once you know they exist.
The two functions that do all the work
Everything in this guide rests on two functions. json_encode() turns a PHP value โ usually an array โ into a JSON string. json_decode() turns a JSON string back into a PHP value. Reading a file is file_get_contents() plus json_decode(); writing a file is json_encode() plus file_put_contents().
<?php
// Reading: file -> string -> PHP array
$json = file_get_contents('settings.json');
$settings = json_decode($json, true);
// Writing: PHP array -> string -> file
$settings['theme'] = 'dark';
file_put_contents('settings.json', json_encode($settings, JSON_PRETTY_PRINT));
The true second argument of json_decode() is the detail most tutorials skip over, so let us settle it first. Without it, json_decode() returns a stdClass object, and you access values with $settings->theme. With true, it returns an associative array, and you write $settings['theme']. Arrays are usually the better choice: they work with the whole family of PHP array functions, they are easier to loop over and merge, and they behave the same way whether the JSON is an object or a list. Unless you have a specific reason to want objects, pass true every time.
Step 1: Reading a JSON file
A safe read checks three things in order: the file exists, the read worked, and the JSON decoded cleanly. Skipping any of these is how null sneaks into your code and causes a confusing error ten lines later.
<?php
declare(strict_types=1);
function loadJson(string $path): array
{
if (!file_exists($path)) {
throw new RuntimeException("JSON file not found: {$path}");
}
$json = file_get_contents($path);
if ($json === false) {
throw new RuntimeException("Could not read JSON file: {$path}");
}
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Invalid JSON in ' . $path . ': ' . json_last_error_msg());
}
return is_array($data) ? $data : [];
}
There are two things worth noticing here. First, json_last_error() is the only way to tell the difference between a file that genuinely contains null and a file whose JSON is broken โ both make json_decode() return null, and only the error check separates them. json_last_error_msg() gives you a human-readable reason, like "Syntax error", which is far more useful in a log than a bare null.
Second, on PHP 8.3 and newer you can do this more cleanly. The JSON_THROW_ON_ERROR flag makes json_decode() throw a JsonException instead of returning null, and the json_validate() function checks whether a string is valid JSON without decoding it at all. If your project runs on PHP 8.3 or later, prefer the flag version โ it turns a silent failure into an exception you cannot accidentally ignore.
<?php
// PHP 8.3+: throw instead of returning null
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
// PHP 8.3+: validate without decoding
if (!json_validate($json)) {
throw new RuntimeException('The file does not contain valid JSON.');
}
Step 2: Working with the decoded data
Once the JSON is a PHP array, it is just an array โ every array function you already know works on it. That is the real payoff of decoding with true: filtering, mapping, sorting, and merging need no special JSON knowledge at all.
<?php
$posts = loadJson('posts.json');
// Keep only published posts
$published = array_values(array_filter(
$posts,
fn (array $post) => ($post['published'] ?? false) === true
));
// Pull out one column
$titles = array_column($published, 'title');
// Change one record in place
foreach ($posts as &$post) {
if ($post['id'] === 3) {
$post['title'] = 'Updated title';
}
}
unset($post); // always unset a reference after a foreach-by-reference
One trap here is the nested structure. JSON objects decode into nested arrays, so a value three levels deep is $data['user']['address']['city']. If any level is missing, PHP throws an "undefined array key" warning and your code keeps going with null. The null coalescing operator is the tidy fix: $data['user']['address']['city'] ?? 'Unknown' returns the fallback instead of warning.
If the decoded data needs sorting, the same array functions apply โ the walkthrough in How to Sort a Multidimensional Array in PHP shows usort() and array_multisort() on exactly this kind of decoded data.
Step 3: Writing a JSON file
Writing looks simple โ encode, then save โ but the flags you pass to json_encode() decide whether the output is readable, correct, and safe to use again later.
<?php
$data = [
'site' => 'Raja Dev Solutions',
'posts' => [
['id' => 1, 'title' => 'Hello World', 'published' => true],
['id' => 2, 'title' => 'Second Post', 'published' => false],
],
];
$json = json_encode(
$data,
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
);
file_put_contents('posts.json', $json, LOCK_EX);
Each flag earns its place. JSON_PRETTY_PRINT indents the output so a human can read and edit the file โ essential for config files, harmless for anything else. JSON_UNESCAPED_UNICODE stops PHP from turning non-English text into \uXXXX escapes, so names and content in Urdu, Arabic, or any other script stay readable in the file. JSON_UNESCAPED_SLASHES keeps URLs as https://example.com instead of https:\/\/example.com. JSON_THROW_ON_ERROR makes encoding failures throw instead of returning false โ encoding usually only fails on invalid UTF-8 or on values that are too deeply nested, but when it happens you want to know immediately.
The LOCK_EX flag on file_put_contents() takes an exclusive lock while writing, so two requests cannot interleave their writes and scramble the file.
Step 4: Writing safely โ never leave a half-written file
LOCK_EX helps, but it does not solve the worst case: a script that dies halfway through writing leaves a truncated file, and the next read finds invalid JSON. The fix is a two-step write โ write to a temporary file first, then rename it over the real file. On every major operating system, rename() replaces the destination in a single atomic step, so any reader sees either the complete old file or the complete new file, never something in between.
<?php
declare(strict_types=1);
function saveJson(string $path, array $data): void
{
$json = json_encode(
$data,
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
);
$temp = $path . '.' . bin2hex(random_bytes(4)) . '.tmp';
if (file_put_contents($temp, $json, LOCK_EX) === false) {
throw new RuntimeException("Could not write temporary JSON file: {$temp}");
}
if (!rename($temp, $path)) {
@unlink($temp);
throw new RuntimeException("Could not replace JSON file: {$path}");
}
}
This is the function to use whenever a JSON file holds data you cannot afford to lose โ user records, settings, or anything a cron job rewrites on a schedule. The temporary file lives in the same directory as the real one, which matters: rename() is only atomic when both files are on the same filesystem, and the same directory guarantees that.
A complete example: a tiny JSON settings store
Putting the pieces together, here is a small settings store you can drop into a project. It loads on construction, lets you get and set values with defaults, and saves safely.
<?php
declare(strict_types=1);
final class JsonStore
{
private array $data;
public function __construct(private string $path)
{
$this->data = file_exists($path) ? loadJson($path) : [];
}
public function get(string $key, mixed $default = null): mixed
{
return $this->data[$key] ?? $default;
}
public function set(string $key, mixed $value): void
{
$this->data[$key] = $value;
}
public function all(): array
{
return $this->data;
}
public function save(): void
{
saveJson($this->path, $this->data);
}
}
$store = new JsonStore(__DIR__ . '/settings.json');
$store->set('maintenance_mode', false);
$store->set('items_per_page', 20);
$store->save();
echo $store->get('items_per_page', 10); // 20
Notice the store keeps the JSON file outside the web root in a real project โ __DIR__ . '/settings.json' here is only for the example. A settings file inside a public directory can be downloaded by anyone who guesses its URL, and if it holds API keys or credentials, that is a breach. Store data files one level above public/, and serve anything the browser needs through a PHP script that checks permission first.
Five mistakes that corrupt JSON data
1. Decoding without checking the error. json_decode() returns null for broken JSON and for the JSON value null alike. Always check json_last_error() or use JSON_THROW_ON_ERROR, or a corrupt file will look like an empty one and your code will happily overwrite it with nothing.
2. Forgetting the true flag and mixing objects with arrays. Decoding without true gives objects, and object syntax (->) does not work with array functions. Pick one style โ associative arrays โ and use it consistently through the whole file.
3. Trusting a file extension. Never decide what a file contains from its name. When you accept a JSON upload, decode it and check json_last_error() โ the extension .json proves nothing.
4. Encoding without JSON_UNESCAPED_UNICODE. By default, json_encode() escapes every non-ASCII character. The file still works, but it becomes unreadable for humans, and a config file nobody can read is a config file nobody will fix.
5. Using a JSON file where a database belongs. JSON files are perfect for settings, small lists, caches, and exports. They are the wrong tool when many users write at the same time, when you need to search or join records, or when the file grows past a few megabytes. At that point the file has to be read and rewritten in full on every change, and a database is faster, safer, and simpler.
When to use JSON files, and when not to
Use a JSON file when the data is small, read far more often than written, and owned by one process at a time: application settings, a cached API response that refreshes hourly, a seed list, or an export. Do not use one for user accounts, orders, or anything with concurrent writers and relations โ that is database work, and pretending otherwise is how data gets lost. JSON is also the format your API speaks, so the same knowledge transfers directly to building endpoints โ see How to Create a REST API in Laravel 13.
#PHP #JSON #FileHandling #WebDevelopment #Backend #ProgrammingTips #RajaDevSolutions

