Assassin Shadow
Assassin Shadow

Reputation: 61

how to update json file with .php?

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

Upvotes: 1

Views: 2720

Answers (2)

Tom
Tom

Reputation: 1613

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;

Upvotes: 1

Oleksii Chernomaz
Oleksii Chernomaz

Reputation: 134

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

Upvotes: 0

Related Questions