1

I am creating a json file from PHP, the idea is to always insert the last record from the database and this record rewrites the results.json file

<?php 

    require_once __DIR__ . '/sql.php';

    $system = new System();

    $sql= $system->SelectLastData();

    $response = array();
    $posts = array();

    while($row=$sql->fetch(PDO::FETCH_ASSOC))
        {
            $id=$row['id']; 
            $name=$row['name']; 
            $posts[] = array('id'=> $id, 'name'=> $name);
        }

    $response['posts'] = $posts;

    $fp = fopen('results.json','w');
    fwrite($fp, json_encode($response, JSON_PRETTY_PRINT));
    fclose($fp);

?>

So far so good, I get the most recent data, pass it through the array and save it in the results.json file

{
    "posts": [
        {
            "id": "50",
            "name": "John Smith"
        }
    ]
}

the problem I have is when writing the results.json file with a new last data, it does not add it, it generates a new results.json file

And what I want is for you to rewrite the file and save one more new data (as in the example), you can help me with that question.

example:

{
    "posts": [
        {
            "id": "50",
            "name": "Charlotte Johnson"
        },
        {
            "id": "51",
            "name": "Emma Jones"
        },
        {
            "id": "52",
            "name": "Benjamin Miller"
        }
    ]
}
2
  • Please, translate your Spanish sentence in English. Commented Feb 9, 2021 at 8:10
  • Sorry, that's it. Commented Feb 9, 2021 at 18:47

1 Answer 1

1

Get existing data from file. Add new data to existing data. Save the file.

$data = json_decode(file_get_contents('results.json'));

while($row=$sql->fetch(PDO::FETCH_ASSOC))
{
    $data->posts[] = array('id'=> $row['id'], 'name'=> $row['name']);
}

file_put_contents('results.json', json_encode($data, JSON_PRETTY_PRINT));

Add sanity checks as necessary. E.g. if the file doesn't exist yet.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, modify my code and it is working as I wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.