How to update/edit a JSON file using PHP

90,218

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);
Share:
90,218

Related videos on Youtube

user475464
Author by

user475464

Updated on July 23, 2022

Comments

  • user475464
    user475464 almost 2 years

    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?

  • user475464
    user475464 almost 11 years
    here '$data[1]' 1 representing node value or activity code?
  • Brewal
    Brewal almost 11 years
    I corrected it, $data[0] is actually {"activity_code":"1","activity_name":"FOOTBALL"}
  • user475464
    user475464 almost 11 years
    i need base on code for example {"activity_code":"TG3","activity_name":"FOOTBALL"} in this case i need to update ACTIVITY_CODE - TG3 to TENNIS
  • user475464
    user475464 almost 11 years
    some thing like where activity_code='TG3' is it possible?
  • Brewal
    Brewal almost 11 years
    This is sql ! See my edit :)
  • user475464
    user475464 almost 11 years
    thanks.. is it possible to go direct to the code with out for loop? something like sql query?
  • Brewal
    Brewal almost 11 years
    This is nonsens, you don't have a database, you can't do a SQL query !
  • user475464
    user475464 almost 11 years
    i asking you is it possible some thing like $data['activity_name'='TG3']['activity_name'] = "TENNIS";
  • zachdyer
    zachdyer almost 6 years
    If you edit the json file logged in as root can php still write to it?
  • Brewal
    Brewal almost 6 years
    @zachdyer As long as you don't change the file permissions it will not have any effect. Make sure that your server user (www or www-data typically) can open this file and you are good to go.
  • Joseph Kreifels II
    Joseph Kreifels II over 3 years
    Can I get help? When I save the new JSON string, the .json file loses everything except for the field updated.
  • Joseph Kreifels II
    Joseph Kreifels II over 3 years
    I Solved it. I had a function do the update while the JSON was loaded on the outside. The variables were out of scope, and since the JSON was hardcoded in the update function, it was just overwriting the entire file with only the key and value I updated