What are some best practices for creating a CSV export from database data in PHP?

When creating a CSV export from database data in PHP, it is important to properly format the data and handle any special characters. One best practice is to use the fputcsv function to write each row of data to the CSV file. Additionally, make sure to set the appropriate headers to indicate that the response is a CSV file.

<?php
// Connect to your database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');

// Query your database to retrieve the data you want to export
$stmt = $pdo->query('SELECT * FROM table');

// Set the headers to indicate that the response is a CSV file
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');

// Open a file pointer to write the CSV data
$fp = fopen('php://output', 'w');

// Write the column headers to the CSV file
fputcsv($fp, ['Column 1', 'Column 2', 'Column 3']);

// Loop through the database results and write each row to the CSV file
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    fputcsv($fp, $row);
}

// Close the file pointer
fclose($fp);
?>