Reputation: 341
I am try to append data in a JSON file with the help of a PHP script. This works but the JSON is added at a wrong position. Which cause my main application to crash. I am a beginner in PHP and thought the community could help me out.
Original JSON:
[
{ "id": 0, "type": "food" },
{ "id": 1, "type": "drinks" },
{ "id": 2, "type": "snacks" }
]
PHP:
<?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)
?>
Updated JSON:
[
{ "id": 0, "type": "food" },
{ "id": 1, "type": "drinks" },
{ "id": 2, "type": "snacks" }
]{"id":"4","type":"drinks"}
Upvotes: 0
Views: 43
Reputation: 3656
Here is your code fixed:
<?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($tempArray);
file_put_contents("data.json", $jsonToEncode)
You must encode full $tempArray
and overwrite the file, not append it.
Generally this code is very dangerous because you're encoding full $_POST
, it lacks some validation.
Upvotes: 2