SyntaxStudy
Sign Up
PHP Beginner 8 min read

JSON File Handling

JSON is the dominant format for configuration files, API payloads, and data exchange. PHP's json_encode() and json_decode() make working with JSON straightforward.

  • json_decode($json, true) — decode to associative array (preferred over stdClass objects).
  • json_encode($data, JSON_PRETTY_PRINT) — encode with readable formatting.
  • Always check json_last_error() or handle exceptions (PHP 7.3+ JSON_THROW_ON_ERROR).
Example
<?php
// Read and parse a JSON file
$configPath = '/var/app/config.json';

$json = file_get_contents($configPath);
if ($json === false) {
    throw new RuntimeException("Cannot read $configPath");
}

$config = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
// JSON_THROW_ON_ERROR throws JsonException instead of returning null

echo $config['database']['host'];
echo $config['app']['debug'] ? 'Debug on' : 'Debug off';

// Write a PHP array as a JSON file
$data = [
    'app'      => ['name' => 'MyApp', 'version' => '1.2.0', 'debug' => false],
    'database' => ['host' => 'localhost', 'port' => 3306, 'name' => 'mydb'],
    'cache'    => ['driver' => 'redis', 'ttl' => 3600],
];

$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
file_put_contents($configPath, $json, LOCK_EX);

// Merge / update a JSON config file safely
function updateJsonFile(string $path, array $updates): void
{
    $existing = file_exists($path)
        ? json_decode(file_get_contents($path), true, 512, JSON_THROW_ON_ERROR)
        : [];

    $merged = array_merge_recursive($existing, $updates);
    $tmp    = $path . '.tmp.' . uniqid();

    file_put_contents($tmp, json_encode($merged, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    rename($tmp, $path);
}
Pro Tip

Tip: Always pass JSON_THROW_ON_ERROR to both json_encode() and json_decode(). Without it, both functions return null / false on error, and it's easy to silently propagate corrupted data through your application.