質問

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)

役に立ちましたか?

解決

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.

他のヒント

If you want to download it as attachment, it is OK not to use fputcsv(), but if you want to use it, here is a workaround:

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

$header = array();
$csv_output = array();
$fields = mysql_num_fields($result);
for ($i = 0; $i < $fields; $i++) {
    $header[] = mysql_field_name($result, $i);
}
$csv_output[] = $header;

while ($rowr = mysql_fetch_array($result)) {
    $csv_output[] = $rowr;
}

$fp = fopen('/path/to/file.csv', 'w');  
foreach ($csv_output as $line) {
    fputcsv($fp, $line);
}
fclose($fp);    

// if you pick up the file from the directory manually, the following is not needed
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=test.csv");
header("Pragma: no-cache");
header("Expires: 0");

print file_get_contents('/path/to/file.csv');
unlink('/path/to/file.csv');
exit;   
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top