How to read and write a JSON file
Short answer
Read the file as a string and parse it:
<?php
$file = sys_get_temp_dir() . '/recipe-settings.json';
file_put_contents($file, '{"theme":"dark","size":14}');
$settings = json_decode(file_get_contents($file), true);
echo $settings['theme'], ' ', $settings['size'];Output:
dark 14Writing
JSON_PRETTY_PRINT makes the file readable, and JSON_UNESCAPED_UNICODE keeps letters as they are:
<?php
$file = sys_get_temp_dir() . '/recipe-settings.json';
$settings = ['theme' => 'light', 'city' => 'Zürich'];
file_put_contents($file, json_encode($settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
echo file_get_contents($file);Output:
{
"theme": "light",
"city": "Zürich"
}A damaged file
With the JSON_THROW_ON_ERROR flag a parse error becomes an exception:
<?php
try {
json_decode('{"theme": "dark",}', true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo 'Broken file: ', $e->getMessage();
}Output:
Broken file: Syntax errorFunctions used in this recipe
- json_decode — Parses a JSON string.
- json_encode — Converts a value to a JSON string.
- file_put_contents — Writes data to a file.