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:
//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.
//Encode the array back into a JSON string.
$json = json_encode($contentsDecoded);
//Save the file.
Step-by-step explanation of the code above.
- We loaded the contents of our file. At this stage, it is a string that contains JSON data.
- We decoded the string into an associative PHP array by using the function json_decode. This allows us to modify the data.
- We incremented our “counter” variable, which is accessible via $contentsDecoded[‘counter’]
- After the change was made, we encoded the PHP array back into a JSON string using json_encode.
- 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!