PHPでjsonファイルを読み書き(連想配列)

よく忘れるのでメモ。

jsonファイルを用意

## data.json
## 下記を記述したjsonファイルを用意
[]

ファイルの読み込み
(参考: 【PHP】json,txtファイルに連想配列を読み込み・書き込みする方法

$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));

書き込み

$array = json_decode($json_file, true);
$array[] = ["name"=>"プリン", "like"=>"good"];
var_dump($array);

file_put_contents($json_filename, json_encode($array, JSON_UNESCAPED_UNICODE), LOCK_EX);

読み込み

$array = json_decode($json_file, true);
foreach ($array as $food) {
  echo $food['name']. ': ' .$food['like']. '<br>';
}