PHP: How to read and write to a JSON file

Updated: January 11, 2024 By: Guest Contributor Post a comment

Introduction

Handling JSON data is an integral part of modern web development. In PHP, reading and writing to JSON files can be easily managed with its built-in functions. This tutorial will walk you through these processes step by step.

Reading JSON Files

Let’s start by reading a JSON file in PHP. The following example demonstrates how to load JSON data from a file:

<?php
// The JSON file
$filename = 'data.json';
// Read the file into a variable
$jsonData = file_get_contents($filename);
// Decode the JSON data into a PHP associative array
$dataArray = json_decode($jsonData, true);
print_r($dataArray);
?>

This block of code will output the contents of ‘data.json’ file as an associative array, allowing you to access the JSON data as you would any other PHP array.

Writing to JSON Files

Now, let’s look at how to write to a JSON file in PHP. This is just as straightforward as reading from one:

<?php
// An associative array of data
$dataArray = [
    'key1' => 'value1',
    'key2' => 'value2',
];

// Encode the data as JSON
$jsonData = json_encode($dataArray, JSON_PRETTY_PRINT);

// The JSON file where to write
$filename = 'output.json';

// Write the JSON data to a file
file_put_contents($filename, $jsonData);
?>

This code snippet will write the associative array into ‘output.json’ file in a nicely formatted way due to the ‘JSON_PRETTY_PRINT’ flag.

Handling Complex JSON Structures

Working with more complex JSON structures might require additional consideration. Let’s examine a code snippet that demonstrates dealing with a nested JSON:

<?php
// A complex associative array (for example, nested arrays)
$complexDataArray = [
    'person' => [
        'name' => 'John Doe',
        'age' => 30,
        'job' => 'Developer'
    ],
    'skills' => ['PHP', 'JavaScript', 'MySQL'],
    'active' => true
];

// encode the array to a JSON string
$jsonData = json_encode($complexDataArray, JSON_PRETTY_PRINT);

// The JSON file
$filename = 'complex_data.json';

// Write the JSON string to the file
file_put_contents($filename, $jsonData);

// Now read and convert it back to an associative array
$readJson = file_get_contents($filename);
$readArray = json_decode($readJson, true);

echo '<pre>';
print_r($readArray);
echo '</pre>';
?>

This code will create a more complex JSON file and then read it back, still providing a clear structure in PHP arrays.

Error Handling in JSON Reading/Writing

No tutorial is complete without discussing error handling. Here’s how you can implement basic error checking when working with JSON files in PHP:

<?php
// Loading JSON data
$jsonData = @file_get_contents($filename);

if ($jsonData === false) {
    die('Error reading the JSON file');
}

// Decoding JSON
$dataArray = json_decode($jsonData, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    die('Error decoding JSON');
}

// Encoding JSON
$jsonData = json_encode($dataArray, JSON_PRETTY_PRINT);

if ($jsonData === false) {
    die('Error encoding JSON');
}

// Writing JSON
if (@file_put_contents($filename, $jsonData) === false) {
    die('Error writing the JSON file');
}
?>

This snippet will halt execution with an appropriate message should any errors arise during the reading or writing processes, by checking the return values and utilizing the `json_last_error()` function after JSON decoding.

Working with JSON File Locking

When dealing with file operations in a multi-user environment, it’s crucial to understand and implement file locking. This ensures that multiple processes don’t write to or read from a file simultaneously, leading to data corruption. Learn to lock and unlock files with PHP when reading and writing JSON:

<?php

class JsonFileManager
{
    private $filePath;

    public function __construct($filePath)
    {
        $this->filePath = $filePath;
    }

    public function readJsonFile(): array
    {
        $this->acquireLock();
        
        // Read JSON file
        $jsonData = file_get_contents($this->filePath);
        $decodedData = json_decode($jsonData, true);

        $this->releaseLock();

        return $decodedData ?? [];
    }

    public function writeJsonFile(array $data): void
    {
        $this->acquireLock();

        // Convert data to JSON
        $jsonData = json_encode($data, JSON_PRETTY_PRINT);

        // Write to JSON file
        file_put_contents($this->filePath, $jsonData);

        $this->releaseLock();
    }

    private function acquireLock(): void
    {
        $lockFile = $this->filePath . '.lock';

        // Attempt to acquire an exclusive lock
        $lockHandle = fopen($lockFile, 'w');
        flock($lockHandle, LOCK_EX);
    }

    private function releaseLock(): void
    {
        $lockFile = $this->filePath . '.lock';

        // Release the lock
        fclose($lockFile);
        unlink($lockFile);
    }
}

// Example usage
$jsonFilePath = 'example.json';
$jsonFileManager = new JsonFileManager($jsonFilePath);

// Read JSON file
$data = $jsonFileManager->readJsonFile();
var_dump($data);

// Modify data
$data['newKey'] = 'New Value';

// Write back to JSON file
$jsonFileManager->writeJsonFile($data);

This code defines a JsonFileManager class that provides methods for reading and writing JSON files with file locking. The acquireLock method is responsible for obtaining an exclusive lock, and the releaseLock method releases the lock. This ensures safe concurrent access to the JSON file in a multi-user environment.

That’s it. Happy coding & have a nice day!