Add, Update, Delete and Read JSON Data/File in PHP
Read JSON File in PHP:
<?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/>"; } ?>
Add to JSON File in PHP:
<?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)); ?>
Update JSON File PHP:
<?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)); ?>
Delete JSON Data from File:
<?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)); ?>
Leave a Comment