Xander
Xander

Reputation: 35

how to add data to existing json file in php

I want to post unlimited form data to a JSON file in php. When I do this:

$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']
        )
      );

the result for on post is:

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

But when I add multiple posts the result is:

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

How can I format the json data correctly on each post submit?

Upvotes: 0

Views: 232

Answers (1)

Xander
Xander

Reputation: 35

I SOLVED IT!

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

Upvotes: 1

Related Questions