1

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.

4
  • 1
    Most would store in database instead of rolling your own file based one Commented Jun 29, 2016 at 20:30
  • What is the purpose of the cars.txt file? Showing how you use it might help find a good solution. Note that if you append another JSON to it, the complete file will no longer be valid JSON. So writing to the same file every time does not seem to give any useful result. Commented Jun 29, 2016 at 20:30
  • I think the JSON you are trying to produce does not look valid. Commented Jun 29, 2016 at 20:33
  • I want to use that txt file as a database in my application. That's why im not sure what should i do .json file or .txt file etc. Commented Jun 29, 2016 at 21:03

2 Answers 2

1

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));
?>
Sign up to request clarification or add additional context in comments.

1 Comment

When i tried this nothing changed. Can you assume why? Does my javascript code has troble with creating json?
0

What you want is probabbly this:

<?php
function read_cars_from_file_and_decode($file) {
    // write a function that reads the content of the file
    // and writes it in decoded form into $cars

    if (!$cars) {
        $cars = array('cars' => array())
    }
    return $cars
}

// depending on the structure of the json POST variable you might
// need to decode $_POST['json'] as user123123123 pointed out
$new_car = $_POST['json'];

// read existing cars from file by calling the function defined above
$file_name = 'cars.json';
$cars = read_cars_from_file_and_decode($file_name)

// append the new car to the array
$cars['car'][] = $new_car;

// write $cars to file again. This needs to be improved to make sure
// the file is completely overwritten. But I leave that to you.
// append definitly doesn't work here so I changed that already.
$info = json_encode($cars, JSON_PRETTY_PRINT);

$file = fopen($file_name, 'w');
fwrite($file, "\n". $info);
fclose($file);
?>

The $json variable is a named array with an array of cars inside. since you only send one car, we simply put the car in the array.

A .json file is essentially also a text file. So yes, you can change it to a json file.

EDIT: I edited my code sample to implement adding of the car to the existing cars in the file.

2 Comments

Nearly like this but whenever i send a request i want to add it into the "car" : [ ] part. Do you get what i mean?
Added that to my answer. Improvements can be made like creating a function for the writing process as well. Also you should consider a database instead of a file (there are also filebased databases!). That would save you a lot of trouble and bring a lot of speed. The way this is going you still have to write deleting of cars from the array, editing of cars and you will face the issue of speed as your cars file starts growing. The way it is written you need to read and write ALL cars from and to the file every time you want to make a change, add or delete one car.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.