15 November, 2016

on Leave a Comment

Shortest way to read/modify/update a JSON config file in PHP

Lets say we have a config file called 'conf.json' which needs to be read and modified via HTML form.
All these codes mentioned below , you can paste in same page.

Here is the php code :

    $jsonString = file_get_contents('conf.json');  //read the json file
    $data = json_decode($jsonString, true);        // decode the json format for processing
    foreach ($data as $key => $entry) {              //make key value pair in a array
        $data[$key] = $entry;

if(isset($_POST['save']))                                 // for save operation
    foreach ($data as $key => $value) {
    $data[$key] = $_POST[$key];
    $newJsonString = json_encode($data);           
    file_put_contents('conf.json', $newJsonString);


HTML code:

<form action="#" method="POST">
<?php foreach ($data as $key => $value): ?>
    <?php echo $key." "; ?> <input type="text" name="<?php echo $key; ?>" value="<?php echo $value; ?>" /><br/>
<?php endforeach; ?>
<button type="submit" name="save">Save</button>


Landing Page eBook WP Shopping Cart

Follow me