1

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 }';
?>
1
  • 1
    You have to decode $jsonString too before pushing it into $fileData array: $fileData[] = json_decode($jsonString); Commented Jul 25, 2014 at 16:38

2 Answers 2

1

Decode the posted JSON:

$fileData[] = json_decode($jsonString);
Sign up to request clarification or add additional context in comments.

Comments

0

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

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.