Search code examples
phpmysqlcsvfputcsv

PHP - Export MySQL query to CSV Changeup


I see plenty of postings about the proper ways to export to CSV, and most developers recommend to use fputcsv()

How would I convert the script below to use fputcsv ? You'll see I'm also exporting the Header row, which reflects the table column names, and I'd like to keep it.

<?php

    $sql = "SELECT * FROM `tbl_customers`";
    $result = mysql_query($sql, $dbdata_conn) or die(mysql_error());


    $header = $csv_output = '';
    $fields = mysql_num_fields($result);
    for ($i = 0; $i < $fields; $i++) {
        $header .= mysql_field_name($result, $i) . ",";
    }
    $header .= "\n";

    while ($rowr = mysql_fetch_row($result)) {
      for ($j=0; $j<$i; $j++) {
        $csv_output .= $rowr[$j].", ";
          }
     $csv_output .= "\n";
    }

    $csv_output = $header.$csv_output;

    header("Content-type: text/x-csv");
    header("Content-Disposition: attachment; filename=test.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    print "$csv_output";
    exit;   

?>

I'm aware that mysql_query is deprecated, so this is for the sake of practice.

As a side note, I'm not familiar with fputcsv, but I am reading that it's rather useful for formatting the data for the csv output, saving us time with all the escapes and such. (I'm also very very open to improvements to what's above)


Solution

  • Simple demonstration (following your mysql_* functions):

    $header=array();
    $fields = mysql_num_fields($result);
    for ($i = 0; $i < $fields; $i++) {
        $header[] = mysql_field_name($result, $i);
    }
    header("...");
    $f=fopen("php://output","wt");
    fputcsv($f,$header);
    while ($row = mysql_fetch_row($result)) {
        fputcsv($f,$row);
    }
    fclose($f);
    

    As you have stated, mysql_* functions are deprecated, so you should work on that too.