Alonso Benites
Alonso Benites

Reputation: 37

Create array with line breaks to rewrite a json (json_encode)

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

Upvotes: 1

Views: 476

Answers (1)

Sharky
Sharky

Reputation: 409

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.

Upvotes: 1

Related Questions