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
- Is it best practice to reach out to the framework developers for support when encountering issues with unfamiliar frameworks in PHP?
- What are the potential drawbacks of distributing data across multiple tables in PHP?
- Are there any best practices or guidelines to follow when creating and reading directories in PHP to avoid errors like the one mentioned in the thread?