如何在php中将数据添加到现有的json文件中

时间:2018-02-01 03:37:37

标签: php json

我想将无限制的表单数据发布到JSON中的php文件中。当我这样做时:

$vals = array(
      array(
          'quest' => $_POST['question'],
          'a' => $_POST['answer_a'],
          'b' => $_POST['answer_b'],
          'c' => $_POST['answer_c'],
          'd' => $_POST['answer_d'],
          'correct' => $_POST['correct_answer']
        )
      );

帖子的结果是:

[
{
    "quest": "HI?",
    "a": "no?",
    "b": "yes?",
    "c": "Maybe?",
    "d": "Nah...",
    "correct": "D"
}
]

但是当我添加多个帖子时,结果是:

[
{
    "quest": "HI?",
    "a": "no?",
    "b": "yes?",
    "c": "Maybe?",
    "d": "Nah...",
    "correct": "D"
}
][
{
    "quest": "HI?",
    "a": "no?",
    "b": "yes?",
    "c": "Maybe?",
    "d": "Nah...",
    "correct": "D"
}
]

如何在每个帖子提交时正确格式化json数据?

1 个答案:

答案 0 :(得分:1)

我解决了它!

if (!file_exists('tempQuestions.json')) {
    $vals[] = array(
        'quest' => $_POST['question'],
        'a' => $_POST['answer_a'],
        'b' => $_POST['answer_b'],
        'c' => $_POST['answer_c'],
        'd' => $_POST['answer_d'],
        'correct' => $_POST['correct_answer']
    );

    $enC = json_encode($vals, JSON_PRETTY_PRINT);
    file_put_contents('tempQuestions.json', $enC, FILE_APPEND);

} else {

    $newz = array();

    $vals[] = array(
    'quest' => $_POST['question'],
    'a' => $_POST['answer_a'],
    'b' => $_POST['answer_b'],
    'c' => $_POST['answer_c'],
    'd' => $_POST['answer_d'],
    'correct' => $_POST['correct_answer']
    );
    $new = file_get_contents('tempQuestions.json');
    $newz = json_decode($new);
    $valz = array_merge($vals, $newz);
    $fp = fopen('tempQuestions.json', 'w');
    $enC = json_encode($valz, JSON_PRETTY_PRINT);
    file_put_contents('tempQuestions.json', $enC, FILE_APPEND);
}