Taha Darendeli Taha Darendeli - 5 months ago 10
Javascript Question

Creating json array and writing it to file

im new in json, php and javascript. I want to save form datas in a json file. I created a form using both html and javascript and created an ajax request to post it php. In my php file im planning to write it to a file. Now my codes work but i want to make it json array. This is what i have right now.

{
"Brand": "Ferrari",
"Model": "458 Italia",
"Year": "2010 - 2015",
"body": "2-seat Berlinetta, 2-seat Spider",
"engine": "4.5L Ferrari F136F V8",
"power": "562bhp @9000rpm",
"torque": "540nm @6000rpm",
"transmission": "7-speed dual clutch",
"topSpeed": "325kph",
"acceleration": "3.3 sec"
}


But I want to do it like this.

{
"cars": [
"Brand": "Ferrari",
"Model": "458 Italia",
"Year": "2010 - 2015",
"body": "2-seat Berlinetta, 2-seat Spider",
"engine": "4.5L Ferrari F136F V8",
"power": "562bhp @9000rpm",
"torque": "540nm @6000rpm",
"transmission": "7-speed dual clutch",
"topSpeed": "325kph",
"acceleration": "3.3 sec"]
}


Should i do it in my php file? Any suggestions which way should i do it? To inform you this is my php file

<?php
$json = $_POST['json'];
$info = json_encode($json, JSON_PRETTY_PRINT);

$file = fopen('cars.txt', 'a');
fwrite($file, "\n". $info);
fclose($file);
?>


and as a last question, as you can see i am using .txt file can i make it to .json file? Does it change anything? Thank you all for you attention.

Answer

In this case you must use also json_decode

<?php
   $json = $_POST["json"];
   $decode = json_decode($json);

   if (!$decode) {
       exit(); // invalid JSON.
   }

   $final = array(
      "cars" => $decode
   );

   file_put_contents("filename.json", json_encode($final, JSON_PRETTY_PRINT));
?>