简体   繁体   English

如何使用JavaScript / PHP将变量数据导出到服务器上的JSON文件?

[英]How to export variable data to a JSON file on the server using JavaScript/PHP?

So let's say I have a HTML page and an input box on it. 假设我有一个HTML页面和一个输入框。 The user will type something in it, then I'll store it as a variable in JS, and then, can I somehow write the data of that variable to an already existing JSON file on the server? 用户将在其中键入一些内容,然后将其存储为JS中的变量,然后可以以某种方式将该变量的数据写入服务器上已经存在的JSON文件中吗?

How can I achieve this using JavaScript and/or PHP? 如何使用JavaScript和/或PHP实现此目的?

EDIT: I actually want to know how to write the data of a PHP variable to a JSON file that is in the same directory as the PHP file. 编辑:我实际上想知道如何将PHP变量的数据写入与PHP文件位于同一目录中的JSON文件。

file_put_contents("json_file.json",json_encode($array));
Result: 结果:
 {"key":"value","anotherkey":"anothervalue"} {“键”:“值”,“另一个键”:“另一个值”} 

Note: file_put_contents function will overwrite your file! 注意: file_put_contents函数将覆盖您的文件!

Edit: appendable: 编辑:可追加:
 $array = json_decode(file_get_contents("json_file.json"),true); $ array = json_decode(file_get_contents(“ json_file.json”),true);\n$array['your_new_key'] = "your_new_value"; $ array ['your_new_key'] =“ your_new_value”;\nfile_put_contents("json_file.json",json_encode($array)); file_put_contents(“ json_file.json”,json_encode($ array)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM