To create a CSV file using PHP, you can use the following code:
<?php
$filename = 'example.csv';
$file_path = '/path/to/csv/folder/' . $filename;
$data = array(
array('Name', 'Email', 'Phone'),
array('John Doe', 'john@example.com', '1234567890'),
array('Jane Doe', 'jane@example.com', '0987654321'),
);
$file = fopen($file_path, 'w');
foreach ($data as $row) {
fputcsv($file, $row);
}
fclose($file);
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.