What are the differences between CSV files and Excel files, and how should PHP developers approach creating each type?
CSV files are plain text files that store tabular data with each row representing a record and each column separated by a delimiter (commonly a comma). Excel files, on the other hand, are binary files that store data in a proprietary format and can contain multiple sheets, formulas, and formatting options. When creating CSV files, PHP developers should use functions like fputcsv() to properly format and write data. For Excel files, libraries like PhpSpreadsheet can be used to generate and manipulate Excel files.
// Creating a CSV file
$csvFile = fopen('data.csv', 'w');
$data = [
['John', 'Doe', 'john.doe@example.com'],
['Jane', 'Smith', 'jane.smith@example.com']
];
foreach ($data as $row) {
fputcsv($csvFile, $row);
}
fclose($csvFile);
// Creating an Excel file
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray($data);
$writer = new Xlsx($spreadsheet);
$writer->save('data.xlsx');