Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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 14

Writing

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 error

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.