1

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

Assassin Shadow
  • 61
  • 1
  • 2
  • 9
  • Bring it into php, file_get_contents, decode it, json_decode, modify as needed, reencode, json_encode, save it back, file_put_contents. Google probably has functional examples. – chris85 Feb 25 '15 at 00:30

2 Answers2

1

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;
Tom
  • 1,563
  • 12
  • 12
  • 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. – Assassin Shadow Feb 25 '15 at 16:41
  • 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. – Tom Feb 25 '15 at 17:24
  • Thank you very much Tom you are awesome indeed – Assassin Shadow Feb 25 '15 at 17:37
  • No probs. Not very scalable this though - you might want to think about a database or something!! Good luck – Tom Feb 25 '15 at 17:56
  • 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 :) – Assassin Shadow Feb 26 '15 at 02:27
0

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));