Created
December 4, 2019 20:29
-
-
Save coulterpeterson/023d02a139c1d103019130f42203c4d7 to your computer and use it in GitHub Desktop.
Write to and read from quick #json data store with #PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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