Skip to content

Instantly share code, notes, and snippets.

@coulterpeterson
Created December 4, 2019 20:29
Show Gist options
  • Save coulterpeterson/023d02a139c1d103019130f42203c4d7 to your computer and use it in GitHub Desktop.
Save coulterpeterson/023d02a139c1d103019130f42203c4d7 to your computer and use it in GitHub Desktop.
Write to and read from quick #json data store with #PHP
/*
* Takes in a new element to be saved, grabs the data array, appends to it, and re-saves it
*/
function saveData( $dataItem ) {
$dataArray = summonData();
array_push($dataArray, $dataItem);
file_put_contents('./records.json', json_encode($dataArray)); // Overwrites the JSON file
chmod('./records.json', 0664);
}
/*
* Returns the decoded JSON array as a PHP array
*/
function summonData(){
$fileName = 'records.json';
$data = file_get_contents($fileName);
$decodedData = json_decode($data);
if( empty($decodedData) ){
return array();
} else {
return $decodedData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment