Are there any best practices for using loops and arrays in PHP to export table data to a CSV file?
When exporting table data to a CSV file using loops and arrays in PHP, it is important to properly format the data and handle special characters to ensure the CSV file is generated correctly. One best practice is to loop through the table data, store each row as an array, and then use fputcsv() function to write the array to the CSV file.
// Sample table data
$tableData = [
['John Doe', 'john.doe@example.com', 'New York'],
['Jane Smith', 'jane.smith@example.com', 'Los Angeles'],
['Mike Johnson', 'mike.johnson@example.com', 'Chicago']
];
// Open a file for writing
$csvFile = fopen('table_data.csv', 'w');
// Loop through table data and write each row to the CSV file
foreach ($tableData as $row) {
fputcsv($csvFile, $row);
}
// Close the file
fclose($csvFile);