Home >Backend Development >PHP Tutorial >How to Generate and Download a CSV File from a MySQL Database using PHP?

How to Generate and Download a CSV File from a MySQL Database using PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-10 21:44:18884browse

How to Generate and Download a CSV File from a MySQL Database using PHP?

How to Create and Download a CSV File for a User in PHP

Question:

A user has requested to retrieve data from a MySQL database as a CSV file. How can a PHP script generate the CSV file and prompt the user to download it when they visit a URL?

Answer:

To create and download a CSV file in PHP:

header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");

function outputCSV($data) {
  $output = fopen("php://output", "wb");
  foreach ($data as $row)
    fputcsv($output, $row); // here you can change delimiter/enclosure
  fclose($output);
}

outputCSV(array(
  array("name 1", "age 1", "city 1"),
  array("name 2", "age 2", "city 2"),
  array("name 3", "age 3", "city 3")
));

Explanation:

  1. Output CSV Header:

    • The header("Content-Type: text/csv") sets the content type to CSV.
    • The header("Content-Disposition: attachment; filename=file.csv") sets the filename for downloading the CSV file and the type of content disposition (attachment).
  2. Output CSV Function (outputCSV):

    • The outputCSV function takes an array of rows as input.
    • It opens a stream for output to php://output.
    • For each row, it uses fputcsv to write the row to the stream. By default, fputcsv uses comma as the field delimiter and double quotes as the enclosure. You can customize these options as needed.
    • Finally, the stream is closed.
  3. Output CSV Data:

    • The outputCSV function is called with an array of data rows.
    • Each row represents a record from the MySQL database.

The above is the detailed content of How to Generate and Download a CSV File from a MySQL Database using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn