如何使用PHP向JSON添加文本[重复]

问题描述 投票:2回答:1

我的网站将文本消息作为输入,我想将这些消息存储在服务器上的“messages.json”中。每当有人输入新消息时,我只想添加一个条目来附加messages.json。

截至目前,我可以将用户的消息($ message)正确发送到“save-message.php”,但是我找不到以正确格式将$ message字符串正确添加到messages.json中的方法。我在尝试使用json_encode($message)时遇到的一个问题是我可以将元素本身添加到文件中,但不是在外部JSON括号内,并且除了最后一个之外都使用逗号,等等。

注意:如果解决方案需要调用JavaScript函数,您是否可以展示如何相应地调整HTML表单和PHP代码?

这是我正在使用的HTML表单:

    <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>

当前save-message.php可以正确地将字符串保存到.txt文件:

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

目标JSON:

 {"messages": [
     {"message":"This is what somebody would enter"},
     {"message":"This is what somebody else would enter"}
 ]}
javascript php jquery html json
1个回答
0
投票

一种方法是将现有的JSON字符串解码为PHP数组并将新消息添加到它。然后再次编码并覆盖现有文件:

<?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);

?>
© www.soinside.com 2019 - 2024. All rights reserved.