Create a CSV File for a user in PHP

Print array to a file
Show a number to two decimal places in PHP

problem statement

If you have data in a MySQL database. You are sending the user a URL to get their data out as a CSV file.

How can you, when they click the link, have a pop-up to download a CVS with the record from MySQL?

solution 1

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")
));

solution 2

Here is an improved version of the function from php.net. Remember to exit() after calling this if you are done with the page.

function download_csv_results($results, $name = NULL)
{
    if( ! $name)
    {
        $name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
    }

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='. $name);
    header('Pragma: no-cache');
    header("Expires: 0");

    $outstream = fopen("php://output", "wb");

    foreach($results as $result)
    {
        fputcsv($outstream, $result);
    }

    fclose($outstream);
}

It is really easy to use and works great with MySQL(i)/PDO result sets.

download_csv_results($results, 'your_name_here.csv');
Print array to a file
Show a number to two decimal places in PHP

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top