我非常喜欢JS,所以希望对PHP有所帮助:]
我有一些数据-POST请求的正文中的JSON-针对PHP文件。php文件需要将进入到现有JSON数组中的每个JSON对象添加到同一文件夹中单独的file.json文件中。我目前有这个:
<?php
$jsonString = file_get_contents("php://input");
$file = file_get_contents("testFile.json");
$fileData = json_decode($file);
$fileData[] = $jsonString;
$dataAsJson = json_encode($fileData);
file_put_contents($file, $dataAsJson);
echo '{ "success": true }';
?>
但是从此开始,它将新的JSON添加到文件中,但不添加到数组中,也不添加逗号来分隔每个对象:
<?php
$jsonString = file_get_contents("php://input");
$file = "testFile.json";
file_put_contents($file, $jsonString, FILE_APPEND);
echo '{ "success": true }';
?>
多亏了这两个答案,这是最终的代码,可以使所有人清楚地了解这个问题。
有两个问题:$ file变量必须仅是文件引用,而不能是'file_get_contents'函数,它被移动来创建一个更完整的$ fileData变量-拉并解码file.json。另一个解决方法是添加@hindmost和@AbraCadaver -thanks提供的json_decode。
<?php
$jsonString = file_get_contents("php://input");
$file = "testFile.json";
$fileData = json_decode(file_get_contents($file));
$fileData[] = json_decode($jsonString);
$dataAsJson = json_encode($fileData);
file_put_contents($file, $dataAsJson);
echo '{ "success": true }';
?>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句