Tags
PHP , file , csv
Asked 3 years ago
30 Jun 2021
Views 322
Ardith

Ardith posted

Creating csv file with php

Creating csv file with php
sachin

sachin
answered Feb 27 '23 00:00

To create a CSV file using PHP, you can use the following code:


<?php
// Define the CSV file name and path
$filename = 'example.csv';
$file_path = '/path/to/csv/folder/' . $filename;

// Define the CSV data to be written to the file
$data = array(
    array('Name', 'Email', 'Phone'),
    array('John Doe', 'john@example.com', '1234567890'),
    array('Jane Doe', 'jane@example.com', '0987654321'),
);

// Open the CSV file for writing
$file = fopen($file_path, 'w');

// Loop through the CSV data and write it to the file
foreach ($data as $row) {
    fputcsv($file, $row);
}

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

// Output a message to the user
echo "CSV file created successfully: " . $filename;
?>




The above code first defines the name and path of the CSV file using the $filename and $file_path variables.

Next, the CSV data is defined as a 2D array using the $data variable. The first row of the array contains the column headers, and each subsequent row contains the data for each record.

The fopen() function is then used to open the CSV file for writing . The second parameter of the fopen() function is set to 'w' to indicate that the file should be opened for writing .

A foreach loop is then used to loop through the CSV data and write each row to the file using the fputcsv() function. The fputcsv() function automatically formats each row as a comma-separated list of values and writes it to the file .

Finally, the fclose() function is used to close the CSV file.

You can change the contents of the $data variable to include your own data. You can also change the column headers by modifying the first row of the $data array. Make sure to set the $file_path variable to the correct path where you want to store the CSV file.
Post Answer