Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
<?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); }
Result
Open