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);
Related videos on Youtube
Author by
user475464
Updated on July 23, 2022Comments
-
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 onactivity_code
How can I achieve this in PHP?
-
user475464 almost 11 yearshere '$data[1]' 1 representing node value or activity code?
-
Brewal almost 11 yearsI corrected it,
$data[0]
is actually{"activity_code":"1","activity_name":"FOOTBALL"}
-
user475464 almost 11 yearsi 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 almost 11 yearssome thing like
where activity_code='TG3'
is it possible? -
Brewal almost 11 yearsThis is
sql
! See my edit :) -
user475464 almost 11 yearsthanks.. is it possible to go direct to the code with out for loop? something like sql query?
-
Brewal almost 11 yearsThis is nonsens, you don't have a database, you can't do a SQL query !
-
user475464 almost 11 yearsi asking you is it possible some thing like
$data['activity_name'='TG3']['activity_name'] = "TENNIS";
-
zachdyer almost 6 yearsIf you edit the json file logged in as root can php still write to it?
-
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 over 3 yearsCan I get help? When I save the new JSON string, the .json file loses everything except for the field updated.
-
Joseph Kreifels II over 3 yearsI 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