write to a json file in php

To write to a JSON file in PHP, you can follow these steps:

  1. Define the data that you want to write to the file in PHP.
  2. Create a file handle using fopen() function with the file path and mode parameters. The mode 'w' opens the file for writing only. If the file doesn't exist, it will be created.
  3. Encode the PHP data to JSON format using json_encode() function.
  4. Write the encoded data to the file using fwrite() function.
  5. Close the file handle using fclose() function.

Here's a sample code to write an array of data to a JSON file in PHP:

main.php
<?php
$data = array(
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'johndoe@example.com'
);

$file = 'data.json';

// Open the file for writing only
$handle = fopen($file, 'w');

// Encode the data to JSON format
$jsonData = json_encode($data, JSON_PRETTY_PRINT);

// Write the encoded data to the file
fwrite($handle, $jsonData);

// Close the file handle
fclose($handle);

echo 'Data successfully written to ' . $file;
?>
436 chars
24 lines

In the above code, the $data array is defined, and the file name and path are specified in the $file variable. A file handle is created using fopen() function, and the $data array is encoded to JSON format using json_encode() function. The encoded data is then written to the file using fwrite() function. Finally, the file handle is closed using fclose() function, and a success message is echoed to the user.

gistlibby LogSnag