Save and Retrieve JSON Data From File

Some of us faces problem while saving file to a local file using PHP and retrieving data from it . Sometimes the output data shows null and nothing happens. Recently i have faced a similar problem. So i have decided to share the code with you. it is very simple. it takes data from a form and save the form data into a file in json format. Every time it takes the data when you click input. Then it reads the data from the file and shows in array format. In this code i have used some filtering and some extra code which is not necessary at all, only for test purpose.



<?php
 $dataArray = $resultArray = [];
 $filename = 'datafile.bak';
 if (isset($_POST['sendvalue']) && !empty($_POST['question']) && !empty($_POST['answer'])) {
 # code...

 $filter = array(',');
 $filter_question = strtolower(str_replace($filter,'|', $_POST['question']));
 $filter_answer = strtolower(str_replace($filter,'|', $_POST['answer']));
 $dataArray['id'] = sha1(md5(rand(0,9999999999)));
 $dataArray['question'] = $filter_question;
 $dataArray['answer'] = $filter_answer;

$data = json_encode($dataArray);
 $data = $data.',';
 $openfile = fopen($filename, 'a') or die('File Not Open !');
 fwrite($openfile, $data);
 fclose($openfile);
 echo 'save complete';
 }
 else {
 echo 'follow the rules';
 }
?>

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title><?php echo $dataArray['question']; ?></title>
</head>
<body>
 <form action="" method="post">
 <p><input type="text" name="question"></p>
 <p><textarea name="answer" rows="10" cols="20"></textarea></p>
 <p><input type="submit" name="sendvalue" value="press this"></p>
 </form>
 <?php
 $openfile = fopen($filename, 'r') or die('File Not Open !');
 $filesize = filesize($filename);
 if ($filesize == 0) {
 # code...
 $filesize = 1;
 }
 $filecontent = fread($openfile, $filesize);
 $filecontent = trim($filecontent, ',');
 $filecontent = '['.$filecontent.']';
 $resultArray = json_decode($filecontent);
 var_dump($resultArray);
 fclose($openfile);
 ?>
</body>
</html>

 

hope this topic helped you a little bit.

Saniul Ahsan

I picked PHP and JavaScript as a career start-up and developed a lot of applications using these. Like Management Application, Web Scrapping, Web API, E-Commerce Solutions, Finance Application etc. Outside of my professional life, I also do projects and code for reputation and my personal portfolio.