What are some best practices for implementing a CSV interface in PHP for data retrieval from a database?
When implementing a CSV interface in PHP for data retrieval from a database, it is important to follow best practices such as properly sanitizing input data, handling errors gracefully, and optimizing performance by fetching data in batches. One common approach is to use the fputcsv function to output data in CSV format.
<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
// Query to retrieve data from the database
$stmt = $pdo->query('SELECT * FROM table');
// Open a file handle for writing CSV data
$fp = fopen('data.csv', 'w');
// Write CSV headers
fputcsv($fp, array('Column 1', 'Column 2', 'Column 3'));
// Fetch and write data in batches
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
fputcsv($fp, $row);
}
// Close the file handle
fclose($fp);
?>