How can you create a CSV file using PHP?Answer

 How can you create a CSV file using PHP?Answer


To create a CSV file using PHP, you can follow these steps:

  1. Open a file using the fopen() function and specify the mode as w to write to the file.
  2. Write the CSV header row, if necessary, using the fputcsv() function.
  3. Loop through your data and write each row to the file using the fputcsv() function.
  4. Close the file using the fclose() function.

Here's an example code snippet that demonstrates how to create a CSV file in PHP:

// Specify the file name and mode $filename = 'data.csv'; $file = fopen($filename, 'w'); // Write the CSV header row $header = array('Name', 'Age', 'Email'); fputcsv($file, $header); // Loop through the data and write each row to the file $data = array( array('John', 30, 'john@example.com'), array('Jane', 25, 'jane@example.com'), array('Bob', 35, 'bob@example.com') ); foreach ($data as $row) { fputcsv($file, $row); } // Close the file fclose($file);


Comments