Append data to a .JSON file with PHP

Append data to a .JSON file with PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Append data to a .JSON file with PHP

Appending raw JSON arrays to a file using fopen in append mode is a common stumbling block for developers transitioning from relational databases to file-based storage. The core issue isn't just writing text; it's maintaining the structural integrity of the JSON array while ensuring unique identifiers are managed correctly without a database engine to handle it.

In your current approach, you are taking the raw POST data and pushing it into an existing array in memory before writing it back. However, there is a critical flaw in how you are handling the file itself. When you open results.json with 'a' (append) and write json_encode($data), you are not appending a new element to the JSON array. You are overwriting the entire file content starting from the first character of the line, or if your logic assumes it's just adding text, you risk creating invalid JSON like [{"id":1},{"id":2}] followed immediately by [{...}], resulting in something that looks like an array but contains two separate structures smashed together without a comma separator.

Valid JSON requires specific delimiters. An array containing multiple objects must be enclosed in square brackets [ and ]. Inside those brackets, individual objects are separated by commas. If you simply append a new object string to the end of the file without ensuring the previous structure was closed and a comma added, the resulting file becomes syntactically invalid.

To solve this while keeping everything in PHP files, you must reconstruct the entire array on every write. The workflow involves reading the existing file content (if any), decoding it into a native PHP array, adding your new data element, re-encoding the complete array, and then writing the whole thing back. This ensures the [ opens once at the very beginning and the ] closes once at the very end.

Here is how you can implement that logic:

// 1. Initialize an empty array to hold our data
$allData = [];

// 2. Attempt to read existing content from the file
if (file_exists('results.json')) {
    $content = file_get_contents('results.json');
    
    // Only decode if the file isn't empty or whitespace
    if (!empty(trim($content))) {
        try {
            $allData = json_decode($content, true);
            
            // Handle potential JSON parse errors (e.g., invalid previous state)
            if (json_last_error() !== JSON_ERROR_NONE) {
                throw new Exception("Invalid JSON detected in existing file.");
            }
        } catch (Exception $e) {
            // If the file is corrupted, start fresh to prevent a broken loop
            $allData = []; 
        }
    }
}

// 3. Add your new data element
// Note: You need an ID generator here because PHP arrays don't auto-increment keys in this context
$newId = max(array_column($allData, 'id', false), 0) + 1;
$newPost = [
    'id' => $newId,
    'title' => $_POST['data']['title'], // Assuming your POST data structure matches the example
    'content' => $_POST['data']['content']
];

$allData[] = $newPost;

// 4. Write the entire reconstructed array back to the file
$fp = fopen('results.json', 'w'); 
fwrite($fp, json_encode($allData));
fclose($fp);

The critical decision here is using 'w' (write) mode instead of 'a' (append) for the final write operation. Since we are reconstructing the entire array in memory by reading the old one, combining it with the new one, and re-encoding, we can safely overwrite the file. This guarantees that the output starts with [ and ends with ], maintaining valid JSON syntax regardless of how many times the script runs.

If you rely on a framework like Laravel, this logic is often handled more elegantly using Eloquent migrations or database seeding, as managing file state manually introduces race conditions if multiple requests hit the server simultaneously. For instance, two concurrent form submissions might read an empty (or stale) version of the file, both calculate ID 1, and overwrite each other's data. While file locking (flock) can mitigate this, a relational database remains the standard for ensuring atomicity and consistency in high-traffic applications.

If you are building a larger application and need robust handling of JSON files or structured data storage, you might consider exploring resources at https://laravelcompany.com to see how modern frameworks abstract these low-level file operations into safer, scalable patterns.

Our network