PHPでフォームに入力された内容をjsonファイルに書き込み

前回の応用

フォームを用意

<form action="" method="post">
 <p>name: <input type="text" name="data[name]" id="name" value=""></p>
 <p>color: <input type="text" name="data[like]" id="color" value=""></p>
 <p><button type="submit" name="submit">送信</button></p>
</form>

ファイルの読み込み

$json_filename = "./data.json";
$json_file = file_get_contents($json_filename);
function print_json($json_file) {
 header('Content-Type: application/json; charset=utf-8');
 $json_file = mb_convert_encoding($json_file, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');
}
//var_dump(json_decode($json_file, true));

フォーム送信時の処理

//フォームが送信されたらやる処理
if(isset($_POST['submit'])) {

 $data = $_POST['data']; //データを配列で取得
 //var_dump($data);

 //jsonファイルに追加、書き込み
 $array = json_decode($json_file, true);
 $array[] = $data;
 //var_dump($array);
 file_put_contents($json_filename, json_encode($array, JSON_UNESCAPED_UNICODE), LOCK_EX);

}