Modifying a JSON file with PHP.

This is a small and simple guide on how to modify a JSON file with PHP. For the purpose of this example, let’s say that our JSON file is called “example.json” and that it contains the following JSON data:

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

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’s the code:

Step-by-step explanation of the code above.

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

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

Comments

comments