Write Data to CSV File in PHP: Step-by-Step Guide

write data to csv with php

The process to write submitted data to a CSV file in PHP involves retrieving the data from the $_POST superglobal array, opening a CSV file for writing using fopen(), creating an array of the data, writing the array as a CSV row to the file using fputcsv(), and closing the file using fclose().

1. Retrieve the submitted data from the $_POST superglobal array:

When a user submits a form, the data they entered is sent to the server via an HTTP POST request. In PHP, you can access this data using the $_POST superglobal array. You should retrieve the data from this array and assign it to variables so that you can use it later.

For example, if you have a form with inputs named name, email, and message, you can retrieve the submitted data like this:

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

2. Open a CSV file for writing using the fopen() function:

Once you have retrieved the submitted data, you need to open a CSV file for writing. You can do this using the fopen() function, which takes two parameters: the file path and the mode.

For example, if you want to save the CSV file in the same directory as your PHP script and name it contact.csv, you can open the file like this:

$fp = fopen('contact.csv', 'a');

The second parameter, ‘a’, specifies that the file should be opened in append mode, which means that new data will be added to the end of the file rather than overwriting existing data.

3. Create an array of the submitted data:

Once you have opened the CSV file, you need to create an array of the submitted data so that you can write it to the file. You can do this by creating a new array and adding the submitted data to it.

For example, you can create an array of the submitted data like this:

$fields = array($name, $email, $message);

4. Write data to CSV row to the file using the fputcsv() function:

Once you have created the array of submitted data, you can write it to the CSV file using the fputcsv() function, which takes two parameters: the file pointer and the array of data.

For example, you can write the array of submitted data to the CSV file like this:

fputcsv($fp, $fields);

This will write a new row to the CSV file with the values of the $name, $email, and $message variables.

5. Close the file using the fclose() function:

Once you have finished writing data to the CSV file, you should close the file using the fclose() function to free up system resources.

For example, you can close the CSV file like this:

fclose($fp);

That’s it! This is a basic example of how to write submitted data to a CSV file in PHP. Note that you should always validate the submitted data and handle errors appropriately in your own code.

You May Also Like