javascript - 如何使用 PHP 将文本添加到 JSON

标签 javascript php jquery html json

<分区>

我的网站将文本消息作为输入,我想将这些消息存储在服务器上的“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>

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

<?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"}
 ]}

最佳答案

一种方法是将现有的 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);

?>

关于javascript - 如何使用 PHP 将文本添加到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47582364/

相关文章:

javascript - 如何使元素指令相对于 ng-repeated 项目的位置?

javascript - 在 php 循环中写入 javascript 数组时如何将新行转换为实际\n

php - 是否可以找出mysql表中哪个字段匹配?

javascript - 守夜人 JS。并行运行不同的测试

javascript - 通过 Ajax 将图像上传到 PHP

javascript - HTML 选择框显示为多个,但要禁用多重选择?

javascript - 不一致的 Javascript 行为(IF 语句嵌套在 while 循环中)

jquery - img src 和 jQuery?

javascript - 转换流程图,使其以 60 秒的间隔动态更新

php - 如何使 Zf2 Apigilty 接受 header 中未设置接受的客户端请求