append to a json file in php

To append data to a JSON file in PHP, you need to open the file with write permission and then write the data to the end of the file.

Here's an example code snippet that demonstrates how to append data to a JSON file using PHP:

main.php
$data = array(
    'name' => 'John',
    'age' => 30
);

$jsonData = json_encode($data);

$file = 'data.json';
$handle = fopen($file, 'a');
fwrite($handle, $jsonData);
fclose($handle);
185 chars
12 lines

In this code snippet, we create a PHP array and encode it to JSON using json_encode(). We then open the file data.json in append mode ('a') with fopen() and write the JSON data to the end of the file using fwrite(). Finally, we close the file using fclose().

Note that it's important to use fclose() to properly close the file after writing to it.

related categories

gistlibby LogSnag