Home > Software engineering >  Struggling to write back to a JSON file from PHP where information comes from a HTML form
Struggling to write back to a JSON file from PHP where information comes from a HTML form

Time:11-09

I am trying to write back to a JSON file from PHP where the information comes from an HTML form.

I cannot understand why it's not writing back.

I have the following code to write back:

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

The variables are:

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

I cannot for the life of me get this to work. The file structure is as follows:

index.php

  • code
  • assets/booking.json

Any help would be greatly appreciated. Thank you!

CodePudding user response:

I assume you want to update the bookings.json when the file exists and create a new one and save the first line when the file does not exist?

If so you can use this code:

$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));
}
  • Related