How do I read and write CSV files in PHP?

In PHP, handling CSV files is straightforward with the use of certain functions that allow you to read and write CSV data easily. Here's a quick overview:

Keywords: PHP, CSV, fgetcsv, fputcsv, file handling
Description: This guide demonstrates how to read from and write to CSV files using PHP, covering basic file operations.

Reading a CSV file in PHP

<?php // Open the CSV file for reading if (($handle = fopen("data.csv", "r")) !== FALSE) { // Read each row of the CSV file while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { // Process the data here print_r($data); } fclose($handle); } ?>

Writing to a CSV file in PHP

<?php // Open the CSV file for writing $file = fopen("output.csv", "w"); // Prepare data to write $data = [ ["Name", "Age", "Email"], ["John Doe", 30, "john@example.com"], ["Jane Doe", 25, "jane@example.com"] ]; // Write each row to the CSV file foreach ($data as $row) { fputcsv($file, $row); } fclose($file); ?>

Keywords: PHP CSV fgetcsv fputcsv file handling