Add, Update, Delete and Read JSON Data/File usingPHP

Tags

, ,


 
jsonResultSet.json

[
    {
        "ID": "1",
        "Name": "Ram ",
        "Sports": "Base Ball"
    },
    {
        "ID": "2",
        "Name": "libero Ram",
        "Sports": "Soccer"
    },
    {
        "ID": "3",
        "Name": "kumar",
        "Sports": "Tennis"
    }
]

Read JSON File in PHP


<?php

$data = file_get_contents('jsonResultSet.json');
$json_array = json_decode($data, true);
foreach ($json_array as $key => $value) {
    echo  $json_array[$key] . " - " .  $json_array[$value] . "<br/>";
}
?>

To Get specific key name :

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


Add to JSON File

<?php 
$data = file_get_contents('jsonResultSet.json');

$json_array = json_decode($data, true);
 
$json_array[] = array('ID'=>4, 'Name'=>'New Name', 'Sports'=>'Cricket');
 
file_put_contents('jsonResultSet.json', json_encode($json_array));
?>

Updated Json like:


[
    {
        "ID": "1",
        "Name": "Ram ",
        "Sports": "Base Ball"
    },
    {
        "ID": "2",
        "Name": "libero Ram",
        "Sports": "Soccer"
    },
    {
        "ID": "3",
        "Name": "kumar",
        "Sports": "Tennis"
    }
    ,
    {
        "ID": "4",
        "Name": "New Name",
        "Sports": "Cricket"
    }
]


Update JSON File 


<?php 
$data = file_get_contents('jsonResultSet.json');
$json_array = json_decode($data, true);

foreach ($json_array as $key => $value) {
    if ($value['ID'] == '2') {
        $json_array[$key]['Sports'] = "Foot Ball";
    }
} 
file_put_contents('jsonResultSet.json', json_encode($json_array));
?>


Delete JSON Data from File:


<?php 
$data = file_get_contents('results.json'); 
$json_array = json_decode($data, true); 
$arr_index = array();
foreach ($json_array as $key => $value)
{
    if ($value['Code'] == "2")
    {
        $arr_index[] = $key;
    }
} 
foreach ($arr_index as $i)
{
    unset($json_array[$i]);
} 
$json_array = array_values($json_array); 
file_put_contents('jsonResultSet.json', json_encode($json_array));
?>