Php 在错误的位置添加了JSON数据
我试图在PHP脚本的帮助下将数据附加到JSON文件中。这是可行的,但是JSON添加到了错误的位置。这导致我的主应用程序崩溃。我是PHP的初学者,认为社区可以帮助我 原始JSON:Php 在错误的位置添加了JSON数据,php,json,Php,Json,我试图在PHP脚本的帮助下将数据附加到JSON文件中。这是可行的,但是JSON添加到了错误的位置。这导致我的主应用程序崩溃。我是PHP的初学者,认为社区可以帮助我 原始JSON: [ { "id": 0, "type": "food" }, { "id": 1, "type": "drinks" }, { "id": 2, "typ
[
{ "id": 0, "type": "food" },
{ "id": 1, "type": "drinks" },
{ "id": 2, "type": "snacks" }
]
PHP:
以下是您的代码修复:
这是您的代码修复:
将json\u encode($node)
更改为json\u encode($tempArray)
并删除FILE\u APPEND
。您需要替换文件中的整个数组,而不仅仅是追加新数组。将json\u encode($node)
更改为json\u encode($tempArray)
并删除file\u append
。您需要替换文件中的整个数组,而不仅仅是附加新数组。
<?php
header("Access-Control-Allow-Origin: *");
$node = ($_POST);
print_r($node);
$json = file_get_contents("data.json");
$tempArray = json_decode($json);
$tempArray[] = $node;
$jsonToEncode = json_encode($node);
file_put_contents("data.json", $jsonToEncode, FILE_APPEND)
?>
[
{ "id": 0, "type": "food" },
{ "id": 1, "type": "drinks" },
{ "id": 2, "type": "snacks" }
]{"id":"4","type":"drinks"}