Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append data to a .JSON file with PHP

Tags:

json

php

I have this .json file:

[
    {
        "id": 1,
        "title": "Ben\\'s First Blog Post",
        "content": "This is the content"
    },
    {
        "id": 2,
        "title": "Ben\\'s Second Blog Post",
        "content": "This is the content"
    }
]

This is my PHP code:

<?php
$data[] = $_POST['data'];

$fp = fopen('results.json', 'a');
fwrite($fp, json_encode($data));
fclose($fp);

The thing is, I'm not exactly sure how to achieve it. I'm going to call this code above every time a form is submitted, so I need the ID to increment and to also keep the valid JSON structure with [ and {, is this possible?

like image 520
benhowdle89 Avatar asked Oct 25 '11 20:10

benhowdle89


People also ask

Can PHP write to a JSON file?

Using PHP scripting we can store a form value in array format. After that will convert the array into JSON data using json_encode() predefined function. Then at last we can move the data to JSON format file.

Can you append to a JSON file?

Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.

Which function is used to append data using JSON?

To append data to the JSON file we have to store the previous data to a variable. To get the data of our JSON file we will be using the file_get_contents() function. The file_get_contents() reads a file into a string.


2 Answers

This has taken the above c example and moved it over to php. This will jump to the end of the file and add the new data in without reading all the file into memory.

// read the file if present
$handle = @fopen($filename, 'r+');

// create the file if needed
if ($handle === null)
{
    $handle = fopen($filename, 'w+');
}

if ($handle)
{
    // seek to the end
    fseek($handle, 0, SEEK_END);

    // are we at the end of is the file empty
    if (ftell($handle) > 0)
    {
        // move back a byte
        fseek($handle, -1, SEEK_END);

        // add the trailing comma
        fwrite($handle, ',', 1);

        // add the new json string
        fwrite($handle, json_encode($event) . ']');
    }
    else
    {
        // write the first event inside an array
        fwrite($handle, json_encode(array($event)));
    }

        // close the handle on the file
        fclose($handle);
}
like image 30
Tom Martin Avatar answered Sep 23 '22 18:09

Tom Martin


$data[] = $_POST['data'];

$inp = file_get_contents('results.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('results.json', $jsonData);
like image 131
Tim Avatar answered Sep 22 '22 18:09

Tim