How to read and write CSV files in PHP?

To read and write CSV files in PHP, you can use the built-in functions fgetcsv() for reading and fputcsv() for writing. Here is an example of reading a CSV file:

$filename = 'data.csv'; // Open the file for reading $file = fopen($filename, 'r'); // Read the header row $headers = fgetcsv($file); // Initialize an empty data array $data = []; // Read the remaining rows while (($row = fgetcsv($file)) !== false) { // Add each row to the data array $data[] = $row; } // Close the file fclose($file); // Print the data array print_r($data);

This code opens the CSV file, reads the header row, and then reads the remaining rows one by one. Each row is added to the $data array. Finally, the file is closed and the data array is printed.

And here is an example of writing data to a CSV file:

$filename = 'data.csv'; // Open the file for writing $file = fopen($filename, 'w'); // Write the header row $headers = ['Name', 'Email', 'Phone']; fputcsv($file, $headers); // Write the data rows $data = [ ['John Doe', '[email protected]', '1234567890'], ['Jane Smith', '[email protected]', '0987654321'] ]; foreach ($data as $row) { fputcsv($file, $row); } // Close the file fclose($file);

This code opens the CSV file in write mode, writes the header row, and then writes each row of data using a foreach loop. Finally, the file is closed.

Note: Make sure you have appropriate read and write permissions for the file or directory you are working with.