How to update/edit a JSON file using PHP

How to update/edit a JSON file using PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Update a JSON Array in PHP Using Activity Codes

Updating specific records within a JSON file is a common requirement when maintaining configuration data, API responses, or local caches. The most robust approach involves treating the JSON file as an associative array structure rather than parsing it into strings. This ensures type safety and prevents issues with special characters or encoding differences that often plague manual string manipulation.

To modify the record where activity_code is "1" from "FOOTBALL" to "TENNIS", you must first deserialize the JSON content into a native PHP array. The json_decode() function handles this conversion, but it defaults to returning an object when given a JSON object (the curly braces {} structure). For complex arrays of objects, as shown in your example, decoding into an object is actually preferred over using JSON_FORCE_OBJECT unless you specifically need to iterate by index.

Here is the standard pattern for reading and modifying the file:

$jsonContent = file_get_contents('data.json');
$data = json_decode($jsonContent);

// Locate the specific item to update
foreach ($data as $item) {
    if ($item->activity_code === '1') {
        $item->activity_name = 'TENNIS';
        break;
    }
}

// Re-encode and overwrite the file
file_put_contents('data.json', json_encode($data, JSON_PRETTY_PRINT));

This approach is efficient because it operates on in-memory objects. However, there are critical considerations regarding how you handle the data structure. If your application relies heavily on indexed access or if json_decode returns an object that isn't compatible with your existing logic, you might need to decode into an associative array using the second parameter of json_decode:

$data = json_decode($jsonContent, true);

When using the associative array format (true), the resulting structure becomes a list of arrays. You would then access properties like $data[0]['activity_name']. This is generally safer for general-purpose scripting because it avoids issues with magic methods in objects and makes the data easier to serialize later if needed.

Handling Large Files and Concurrent Access

While the above method works perfectly for small to medium-sized files, you must consider file locking if multiple processes might try to write to data.json simultaneously. Without proper synchronization, one process could overwrite the changes made by another, leading to data loss or corruption.

In a production environment, you should use file locking before reading and writing. PHP provides flock() for this purpose:

$file = fopen('data.json', 'r+');
flock($file, LOCK_EX); // Exclusive lock

// Read current content
$jsonContent = stream_get_contents($file);
rewind($file);

// Modify data as needed
$data = json_decode($jsonContent);
foreach ($data as $item) {
    if ($item->activity_code === '1') {
        $item->activity_name = 'TENNIS';
        break;
    }
}

// Write back
rewind($file);
ftruncate($file, 0);
fwrite($file, json_encode($data, JSON_PRETTY_PRINT));

flock($file, LOCK_UN); // Release lock
fclose($file);

Verification and Error Handling

Always validate that json_decode did not fail before attempting to modify the data. If the file contains malformed JSON, json_last_error() will return an error constant like JSON_ERROR_SYNTAX. Attempting to iterate over a failed decode results in warnings or undefined property access errors.

Furthermore, ensure that the updated string is valid JSON before writing it back. The json_encode function returns false if encoding fails. While rare for simple updates, this check prevents silent data corruption.

If you are working within a Laravel application, consider whether modifying a raw JSON file is the best architectural choice. For dynamic data management, leveraging Laravel's built-in migrations or database relations is often superior to maintaining static JSON files. However, if your use case strictly requires file-based storage, this method provides a reliable, low-level mechanism to update records based on unique keys like activity_code.

For advanced needs involving complex API integrations or enterprise-grade data management, you might find additional resources at https://laravelcompany.com.

Our network