前提
PHP初学者で、現在データを取得する方法について学習しています
VScodeを使っています
実現したいこと
PHPを使用してデータをJSONファイルに追加したい
発生している問題・エラーメッセージ
JSONファイルが存在しません
該当のソースコード
PHP
1<?php 2 $message = ''; 3 $error = ''; 4 if(isset($_POST["submit"])) 5 { 6 if(empty($_POST["name"])) 7 { 8 $error = "<label class='text-danger'>Enter Name</label>"; 9 } 10 else if(empty($_POST["gender"])) 11 { 12 $error = "<label class='text-danger'>Enter Gender</label>"; 13 } 14 else if(empty($_POST["designation"])) 15 { 16 $error = "<label class='text-danger'>Enter Designation</label>"; 17 } 18 else 19 { 20 if(file_exists('employee_data.json')) 21 { 22 $current_data = file_get_contents('employee_data.json'); 23 $array_data = json_decode($current_data, true); 24 $extra = array( 25 'name' => $_POST['name'], 26 'gender' => $_POST["gender"], 27 'designation' => $_POST["designation"] 28 ); 29 $array_data[] = $extra; 30 $final_data = json_encode($array_data); 31 if(file_put_contents('employee_data.json', $final_data)) 32 { 33 $message = "<label class='text-success'>File Appended Success fully</p>"; 34 } 35 } 36 else 37 { 38 $error = 'JSONファイルが存在しません'; 39 } 40 } 41 } 42 ?> 43 <!DOCTYPE html> 44 <html> 45 <head> 46 <title>Webslesson Tutorial | Append Data to JSON File using PHP</title> 47 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 48 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> 49 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> 50 </head> 51 <body> 52 <br /> 53 <div class="container" style="width:500px;"> 54 <h3 align="">Append Data to JSON File</h3><br /> 55 <form method="post"> 56 <?php 57 if(isset($error)) 58 { 59 echo $error; 60 } 61 ?> 62 <br /> 63 <label>Name</label> 64 <input type="text" name="name" class="form-control" /><br /> 65 <label>Gender</label> 66 <input type="text" name="gender" class="form-control" /><br /> 67 <label>Designation</label> 68 <input type="text" name="designation" class="form-control" /><br /> 69 <input type="submit" name="submit" value="Append" class="btn btn-info" /><br /> 70 <?php 71 if(isset($message)) 72 { 73 echo $message; 74 } 75 ?> 76 </form> 77 </div> 78 <br /> 79 </body> 80 </html>
試したこと
JSONファイル(employee_data.json)を作成しました
補足情報(FW/ツールのバージョンなど)
https://www.webslesson.info/2016/04/append-data-to-json-file-using-php.html
を参考にしています
回答1件