Add, Update, Delete and Read JSON Data/File in PHP

Hi! Today let's see about JSON CRUD with PHP. Yep! Manipulating json data - add, update (edit), delete and read json file using php script. JSON is everywhere these days. With increasing popularity of APIs it's a must for a developer to know how to read, parse and manipulate json data. If you wonder what the connection between API and JSON is, almost all modern APIs lean towards REST and they provide response as JSON. (In KodingMadeSimple.com I have covered json topics a lot earlier and you can visit our JSON Tutorials section to learn more about working with JSON format.)

php add edit delete read json file

JSON is the string notation of JavaScript object. It takes up simple to complex forms and stores data as (key, value) pairs.

This is the example of a json file.

Read Also:

results.json

[
    {
        "Code": "1",
        "Name": "June Zupers",
        "Sports": "Base Ball"
    },
    {
        "Code": "2",
        "Name": "Fred Cortez",
        "Sports": "Soccer"
    },
    {
        "Code": "3",
        "Name": "Kevin Burks",
        "Sports": "Tennis"
    }
]

Now let me show you how to read and parse through above json file using php.

Read JSON File in PHP:

To read json file with php, you must first get the json data stored in the file, decode json and finally parse through the array or object.

For that you'll need two php functions - one is file_get_contents() and the other is json_decode().

<?php
// load file
$data = file_get_contents('results.json');

// decode json to associative array
$json_arr = json_decode($data, true);

foreach ($json_arr as $key => $value) {
    echo  $json_arr[$key] . " - " .  $json_arr[$value] . "<br/>";
}
?>

If you know the specific key name, then you can simply access it like this,

echo $json_arr[0]['Code'];

Note: The function json_decode() decodes the given json string into an array or object. For example the statement json_decode($data, true); in above code will return associative array. You can ignore the second parameter 'true' to make it return as an object.

Add to JSON File in PHP:

To add additional records to json file you have to simply append it to the end of file. Here let's see an example for adding new data. The following php snippet takes up a json file, decode it, add extra records and again encode to json and save it into a new file.

<?php
// read json file
$data = file_get_contents('results.json');

// decode json
$json_arr = json_decode($data, true);

// add data
$json_arr[] = array('Code'=>4, 'Name'=>'Jeff Darwin', 'Sports'=>'Cricket');

// encode json and save to file
file_put_contents('results_new.json', json_encode($json_arr));
?>

results_new.json

[
    {
        "Code":"1",
        "Name":"June Zupers",
        "Sports":"Base Ball"
    },
    {
        "Code":"2",
        "Name":"Fred Cortez",
        "Sports":"Soccer"
    },
    {
        "Code":"3",
        "Name":"Kevin Burks",
        "Sports":"Tennis"
    },
    {
        "Code":4,
        "Name":"Jeff Darwin",
        "Sports":"Cricket"
    }
]

Update JSON File PHP:

As for updating json file you can either modify single value or in bulk. Here's an example for modifying value for a specific json attribute.

<?php
// read file
$data = file_get_contents('results.json');

// decode json to array
$json_arr = json_decode($data, true);

foreach ($json_arr as $key => $value) {
    if ($value['Code'] == '2') {
        $json_arr[$key]['Sports'] = "Foot Ball";
    }
}

// encode array to json and save to file
file_put_contents('results_new.json', json_encode($json_arr));
?>

Here's what the script does.

  • Load results.json file to a variable
  • Decode json data to array
  • Loop through the array and check if key 'Code' is '2'
  • And edit the corresponding 'Sports' value to 'Foot Ball'

results_new.json

[
    {
        "Code":"1",
        "Name":"June Zupers",
        "Sports":"Base Ball"
    },
    {
        "Code":"2",
        "Name":"Fred Cortez",
        "Sports":"Foot Ball"
    },
    {
        "Code":"3",
        "Name":"Kevin Burks",
        "Sports":"Tennis"
    }
]

Delete JSON Data from File:

JSON deletion is little complex since it is easy to mess up doing the process. You must be clear what you need to delete first, a specific key pair from all rows or a complete row.

For example this php script will delete entire record from json containing key 'Code' as '2'.

<?php
// read json file
$data = file_get_contents('results.json');

// decode json to associative array
$json_arr = json_decode($data, true);

// get array index to delete
$arr_index = array();
foreach ($json_arr as $key => $value)
{
    if ($value['Code'] == "2")
    {
        $arr_index[] = $key;
    }
}

// delete data
foreach ($arr_index as $i)
{
    unset($json_arr[$i]);
}

// rebase array
$json_arr = array_values($json_arr);

// encode array to json and save to file
file_put_contents('results_new.json', json_encode($json_arr));
?>

And this is the file we get after deletion.

[
    {
        "Code":"1",
        "Name":"June Zupers",
        "Sports":"Base Ball"
    },
    {
        "Code":"3",
        "Name":"Kevin Burks",
        "Sports":"Tennis"
    }
]

The deletion script uses two foreach loops. The first one is for determining the array index we need to delete from json.

And the second is what actually deletes from array using unset() function.

Finally it rebases the array, encode it to json and store it in a new file.

Read Also:

Likewise you can add, edit, delete and read json file in php. It's easy to mess up with json and so many newbies confuses json and actual javascript object. JSON can get complex if it uses nested structure and you'll have real trouble manipulating it. Only constant practice will get you there and it's easy to master it in my opinion.

I hope you like this tutorial. Please don't forget to share it with your friends.

1 comment:

  1. // unset($json_arr[$i]); will remove wrong row

    // i suggest modify like this -----------------

    // delete data ------------------------
    foreach ($arr_index as $key2 => $val2)
    {
    unset($json_arr[$val2]);
    }

    ReplyDelete