Home » Php » How to update/edit a JSON file using PHP

How to update/edit a JSON file using PHP

Posted by: admin April 23, 2020 Leave a comment

Questions:

Here is my JSON

[
   {
      "activity_code":"1",
      "activity_name":"FOOTBALL"
   },
   {
      "activity_code":"2",
      "activity_name":"CRICKET"
   }
]

I need to update {"activity_code":"1","activity_name":"FOOTBALL"} to {"activity_code":"1","activity_name":"TENNIS"} based on activity_code

How can I achieve this in PHP?

How to&Answers:

First, you need to decode it :

$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);

Then change the data :

$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
    if ($entry['activity_code'] == '1') {
        $data[$key]['activity_name'] = "TENNIS";
    }
}

Then re-encode it and save it back in the file:

$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);