PHP read and write JSON from file

PHP read and write JSON from file

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

Stefan Bogdanescu

Founder & Senior Architect

PHP read and write JSON from file

Attempting to modify a JSON structure stored on disk is a common task, but getting it right requires understanding how PHP's json_decode function behaves by default. The core issue in the provided snippet stems from a subtle type mismatch that occurs when reading the file into memory.

When you execute json_decode(file_get_contents($file)) without passing a second argument to the function, PHP defaults to returning an object of type stdClass. While this works fine for accessing properties via string keys (e.g., $json->bgates), it prevents you from using array-style syntax (e.g., $json[$user]) because stdClass is not an array. This results in the specific fatal error: "Cannot use object of type stdClass as array."

To resolve this, you must explicitly instruct PHP to return an associative array instead. You achieve this by passing true as the second argument to json_decode. This changes the return type from stdClass to array, allowing standard array operations like pushing new keys or iterating over existing ones.

Here is the corrected logic for adding a new entry:

<?php

$user = "bross";
$first = "Bob";
$last = "Ross";

$file = "list.txt";

// Decode JSON into an associative array by passing true as the second argument
$json = json_decode(file_get_contents($file), true);

// Now we can use array syntax to add new data
$json[$user] = ["first" => $first, "last" => $last];

// Encode back to JSON and write to file
// Note: We will discuss the order of keys below
file_put_contents($file, json_encode($json));

?&gt;

While this approach solves the immediate crash, there is a significant consideration regarding data integrity when modifying JSON files: key ordering. In the original example, the JSON object has keys bgates and sjobs. When you decode it into an array and add a new key bross, PHP stores this in memory using the internal ZEND_HASH structure (in older versions) or hash tables. When you subsequently run json_encode without specific flags, PHP does not guarantee that the resulting JSON will preserve the original key order exactly as it appeared in the source file, nor does it necessarily append the new key at the very end in a predictable way across all versions if hashing collisions occur.

If maintaining strict lexicographical or insertion-order fidelity is critical for your application (which is often the case when generating API responses or storing configuration), you should use the JSON_UNESCAPED_UNICODE flag combined with careful handling, or better yet, read the file as a string and manually insert the new data if the structure is simple. However, for most general purposes, decoding to an array, modifying it, and re-encoding is sufficient.

There is also the matter of error handling. Relying on file_get_contents without checking if the file exists or if the decode operation was successful can lead to silent failures or unexpected behavior. It is best practice to wrap the logic in checks: verify that json_last_error() returns JSON_ERROR_NONE before attempting to modify the data structure. If the JSON is malformed, modifying it blindly will result in undefined behavior.

Furthermore, be mindful of PHP versions. The source material mentions PHP 5.2. In that version, json_decode returning an object was the default behavior, and the distinction between decoding to an array or object was crucial. Modern PHP versions (7.0+) handle this similarly, but the ecosystem has evolved. If you are working in a modern stack, consider whether updating the source JSON schema is a valid option before trying to patch it programmatically.

For projects built on the Laravel framework, there are robust utilities that abstract away these low-level file handling details. The LaravelCompany community often discusses best practices for data persistence where such manual file manipulation might be replaced by database interactions or dedicated storage drivers to ensure atomic writes and proper locking mechanisms are in place. However, if you must stick to flat files, always remember that file_put_contents is not atomic; concurrent writes can corrupt the JSON structure, so external locking strategies may be necessary in high-traffic environments.

Our network