I have a json file on my server that I would like to update using a php file. By update I mean put new key value pairs. Is it possible for anyone to point me to the right direction? A tutorial or an example perhapes? Thank you
2 Answers
Here's a simple example...
<?php
// Define the file here
define('JSON_FILE', '/tmp/data.json');
// Create the empty file
if(!file_exists(JSON_FILE)) {
$int_bytes = file_put_contents(JSON_FILE, json_encode((object)[
'events' => ['First entry']
]));
echo "Wrote {$int_bytes} bytes to new file", PHP_EOL;
}
// Load and decode
$obj_data = json_decode(file_get_contents(JSON_FILE));
// Show the data after loading
print_r($obj_data);
// Set some data
$obj_data->awesome = true;
$obj_data->name = "tom";
// Add an event to the array
$obj_data->events[] = "Event at " . time();
// Show the data before saving
print_r($obj_data);
// Encode and save!
$int_bytes = file_put_contents(JSON_FILE, json_encode($obj_data));
echo "Wrote {$int_bytes} bytes", PHP_EOL;
5 Comments
Assassin Shadow
this kind of replaces all the data in my .json file. but I wanted to update my .json file. I mean like add new data while the old data would still be intact.
Tom
OK... you can just use an array in the JSON data, like this: $obj_data->events[] = 'Next entry'; - assuming the "events" property is an array. I'll update my answer with a sample.
Assassin Shadow
Thank you very much Tom you are awesome indeed
Tom
No probs. Not very scalable this though - you might want to think about a database or something!! Good luck
Assassin Shadow
The new sample for some reason does not work but if i remove "if(!file_exists(JSON_FILE)) { $int_bytes = file_put_contents(JSON_FILE, json_encode((object)[ 'events' => ['First entry'] ])); echo "Wrote {$int_bytes} bytes to new file", PHP_EOL; }" this then it does the job :)
you will have something like this:
$yourFileContent = file_get_contents($pathToFileWithJson); //<-- but note that file should contain ONLY valid JSON without any other symbols
//you can also add validation here if you managed to get something, etc...
$yourFileContent = json_decode($yourFileContent,true);
//then you can also add validation if you managed to parse json. if failled to parse, you can process it separately.
$yourFileContent+=array('newKey'=>'newValue','newKey2'=>'newValue2'); //<--add keys if not exists (actual only for dictionaries)
file_put_contents($pathToFileWithJson,json_encode($yourFileContent));