我在json,php和javascript中的新功能。我想在json文件中保存表单数据。我使用html和javascript创建了一个表单,并创建了一个ajax请求来发布它。在我的PHP文件中我计划将其写入文件。现在我的代码工作,但我想使它成为json数组。这就是我现在所拥有的。
var input = {
UserId: "11111111-1111-1111-1111-111111111111",
Location: {
Latitude: "anotherLatitude",
Longitude: "anotherLongitude"
}
};
但我想这样做。
{
"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"
}
我应该在我的php文件中这样做吗?我应该以哪种方式做到这一点?告诉你这是我的php文件
{
"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"]
}
并且作为最后一个问题,你可以看到我正在使用.txt文件,我可以将其转换为.json文件吗?它有什么改变吗?谢谢大家的关注。
答案 0 :(得分:1)
在这种情况下,您还必须使用 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));
?>
答案 1 :(得分:0)
你想要的可能是这个:
<?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);
?>
$ json变量是一个命名数组,里面有一系列汽车。因为你只发一辆车,我们只需把车放在阵列中。
<。> .json文件本质上也是一个文本文件。所以,是的,您可以将其更改为json文件。编辑:我编辑了我的代码示例,以实现将汽车添加到文件中的现有汽车。