努力从 PHP 写回 JSON 文件,其中信息来自 HTML 表单

Struggling to write back to a JSON file from PHP where information comes from a HTML form

我正在尝试从 PHP 写回 JSON 文件,其中信息来自 HTML 表格。

我不明白为什么它不回信。

我有以下代码回写:

if($name)
{
  if(file_exists('Location: ../assets/bookings.json'))
  {
    $bookingJson[] = array("name"=>$name,"surname"=>$surname,"email"=>$email,
    "checkIn"=>$checkIn,"checkOut"=>$checkOut,"hotel"=>$hotel);
  } else {
    {
      $bookingJson = [];
    }
  }
  file_put_contents('Location: ../assets/bookings.json', json_encode($bookingJson, JSON_PRETTY_PRINT));
}

变量是:

$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$checkIn = $_POST['checkIn'];
$checkOut = $_POST['checkOut'];
$hotel = $_POST['hotel'];

$name = trim($name);
$surname = trim($surname);
$email = trim($email);
$checkIn = trim($checkIn);
$checkOut = trim($checkOut);
$hotel = trim($hotel);

我这辈子都做不到。文件结构如下:

index.php

如有任何帮助,我们将不胜感激。谢谢!

我假设您想在文件存在时更新 bookings.json 并在文件不存在时创建一个新文件并保存第一行?

如果是这样,您可以使用此代码:

$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$checkIn = $_POST['checkIn'];
$checkOut = $_POST['checkOut'];
$hotel = $_POST['hotel'];

$name = trim($name);
$surname = trim($surname);
$email = trim($email);
$checkIn = trim($checkIn);
$checkOut = trim($checkOut);
$hotel = trim($hotel);

$file = '../assets/bookings.json';

if($name)
{
  if(file_exists($file))
  {
    $bookingJson = json_decode(file_get_contents($file));
  } else {
    $bookingJson = [];
  }
   $bookingJson[] = array("name"=>$name,"surname"=>$surname,"email"=>$email,
    "checkIn"=>$checkIn,"checkOut"=>$checkOut,"hotel"=>$hotel);
  file_put_contents($file, json_encode($bookingJson, JSON_PRETTY_PRINT));
}