typeofgraphic
typeofgraphic

Reputation: 322

Append JSON to array in file using PHP

I am very much a JS person so some help with PHP would be appreciated :]

I have some data - JSON in the body of a POST request - which targets a PHP file. The php file needs to add each JSON object that comes in to an existing JSON array in a separate file.json file in the same folder. I have this currently:

<?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 }';
?>

But started with this, which adds new JSON to the file but not in an array or with commas to separate each object:

<?php

$jsonString = file_get_contents("php://input");

$file = "testFile.json";

file_put_contents($file, $jsonString, FILE_APPEND);
echo '{ "success": true }';
?>

Upvotes: 1

Views: 603

Answers (2)

typeofgraphic
typeofgraphic

Reputation: 322

Thanks to both answers, here is the final code to give full clarity to anyone who comes to this question.

There were two problems: the $file variable had to be just the file reference and not the 'file_get_contents' function, this was moved to create a more complete $fileData variable - to pull and decode the file.json. The other fix was adding json_decode as given by @hindmost and @AbraCadaver -thanks.

<?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 }';

?>

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

Decode the posted JSON:

$fileData[] = json_decode($jsonString);

Upvotes: 1

Related Questions