2

My website takes in text messages as input, and I want to store these messages in "messages.json" on the server. Every time somebody enters a new message, I simply want to append messages.json with one more entry.

As of now, I can get the user's message ($message) properly sent to "save-message.php", but I couldn't find a way to properly add that $message string into messages.json in the correct format. One issue I was running into when experimenting with json_encode($message) was I could add the elements themselves to the file, but not inside the outer JSON brackets and with a comma after all them except the last one, etc.

Note: If solution requires a call to a JavaScript function, could you show how to adjust the HTML form and the PHP code accordingly to?

Here is my HTML form I am using:

    <form action="/save-message.php" method="POST">
        <textarea name="message" placeholder="Enter your anonymous message here!"></textarea>
        <input id="submitNoteButton" type="submit" value="Submit mystery note"/>
    </form>
</div>

Current save-message.php that can properly save strings to a .txt file:

<?php
    $file = 'messages.txt';
    $message = $_POST['message'];
    file_put_contents($file, $message, FILE_APPEND | LOCK_EX);
    header('Location: /note_submitted.html'); // Redirect
?>

Goal JSON:

 {"messages": [
     {"message":"This is what somebody would enter"},
     {"message":"This is what somebody else would enter"}
 ]}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

0

One way to do it would be to decode the existing JSON string into a PHP array and add the new message(s) to it. Then just encode it again and overwrite the existing file:

<?php
// Used as an example. Replace with file_get_contents();
$json = '{"messages": [ {"message":"This is what somebody would enter"}, {"message":"This is what somebody else would enter"} ]}';

// Decode the json string to a PHP array
$decode = json_decode($json, true);

// Push the new data to the array. Used an example here
// Just replace "This is a test" with $_POST['message'];
array_push($decode['messages'], array("message" => "This is a test"));

// To see the result as an array, use this:
echo "<pre>";
print_r($decode);
echo "</pre>";

// Encode the array back to a JSON string
$encode = json_encode($decode);

// To see the result, use this:
echo $encode;

// Put it back in the file:
file_put_contents("messages.json", $encode, LOCK_EX);

?>
icecub
  • 8,615
  • 6
  • 41
  • 70