What is the best method to generate a CSV file from a database query in PHP?
To generate a CSV file from a database query in PHP, you can fetch the data from the database using a query, then loop through the results and write them to a CSV file using the fputcsv() function. This function allows you to easily format the data as CSV and write it to a file.
<?php
// Connect to the database
$conn = new mysqli('localhost', 'username', 'password', 'database');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform a database query
$result = $conn->query("SELECT * FROM table");
// Create a new file for writing
$fp = fopen('output.csv', 'w');
// Write the column headers to the CSV file
fputcsv($fp, array('Column1', 'Column2', 'Column3'));
// Loop through the results and write each row to the CSV file
while ($row = $result->fetch_assoc()) {
fputcsv($fp, $row);
}
// Close the file
fclose($fp);
// Close the database connection
$conn->close();
echo "CSV file generated successfully";
?>
Keywords
Related Questions
- What are some best practices for replacing placeholders in PDF documents with form data using str_replace in PHP to avoid errors?
- What are the potential pitfalls of storing sensitive data, such as database parameters, directly in PHP classes?
- What are some best practices for structuring SQL queries in PHP to efficiently retrieve and display images from a database in a gallery format?