Modifying a JSON file with PHP.

In this guide, we are going to show you how to modify a JSON file using PHP.

For the purpose of this example, let’s say that our JSON file is example.json. Furthermore, this file contains the following JSON data.

{"counter":0}

As you can see, our file contains a small bit of JSON data. We have one variable called “counter”, which is set to zero.

The goal here is to add +1 onto this counter.

For the purpose of this example, we will modify the counter variable whenever our page is loaded. Nothing fancy, just some basic incrementation.

The first order of business is to load the JSON file and decode the data so that we can modify it. To do this, will will use the functions file_get_contents and json_decode.

Here is the code.

//Load the file
$contents = file_get_contents('example.json');

//Decode the JSON data into a PHP array.
$contentsDecoded = json_decode($contents, true);

//Modify the counter variable.
$contentsDecoded['counter']++;

//Encode the array back into a JSON string.
$json = json_encode($contentsDecoded);

//Save the file.
file_put_contents('example.json', $json);

A step-by-step explanation of the code above.

  1. Firstly, we load the contents of the file. At this stage, it is a string that contains JSON data.
  2. We then decode the string into an associative PHP array by using the function json_decode. This will make it easier for us to modify the data.
  3. After that, we incremented our “counter” variable, which is accessible via the $contentsDecoded[‘counter’] element.
  4. After the change is made, we encode the PHP array back into a JSON string using json_encode.
  5. Finally, we modify our file by replacing the old contents of with the newly-created JSON string.

And that’s it. Done!

As you can see, modifying a JSON file with PHP is actually pretty simple!