Are there any specific PHP libraries or tools that are recommended for exporting MySQL data to CSV format?
To export MySQL data to CSV format in PHP, you can use the `fputcsv` function to write data to a CSV file. You can fetch the data from MySQL using a query and then loop through the results to write each row to the CSV file. It's recommended to use PHP's PDO extension for connecting to MySQL and executing queries.
<?php
// Connect to MySQL database using PDO
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');
// Query to fetch data from MySQL
$stmt = $pdo->query("SELECT * FROM table_name");
// Open a file handle for writing CSV data
$fp = fopen('exported_data.csv', 'w');
// Write column headers to CSV file
fputcsv($fp, array('Column 1', 'Column 2', 'Column 3'));
// Loop through the results and write each row to the CSV file
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
fputcsv($fp, $row);
}
// Close the file handle
fclose($fp);
echo 'Data exported to CSV successfully';
?>
Keywords
Related Questions
- How can a while loop be used in PHP to read text line by line and split it after a certain character limit?
- What are the best practices for adding elements into a multidimensional array in PHP?
- When implementing progress bars in PHP, what are some common mistakes to avoid in terms of logic and initialization of the progress bar object?