0

I am having some trouble exporting a CSV file using fputcsv. The file downloads but it is blank. I have tried exporting to xls and it works perfectly but I wanted to use csv with custom field headers as shown in code below. I am not sure if I am doing something wrong or if I need to have any php.ini changes done. I know I have fopen enabled but the file is about 6.5mb of database information.

Thanks in advance!

$colnames = array(
'forDepts' => "Member No.",
'clientId' => "Date joined",
'createdOn' => "Title",
'createdBy' => "First name",
'description' => "Notes"
);

function map_colnames($input)
{
global $colnames;
return isset($colnames[$input]) ? $colnames[$input] : $input;
}

function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
  $str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
$str = mb_convert_encoding($str, 'UTF-16LE', 'UTF-8');
}

// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";

header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv; charset=UTF-16LE");



$out = fopen("php://output", 'w');

$flag = false;

$result = mysql_query("SELECT forDepts, clientId, createdOn, createdBy, description FROM notes") or die('Query failed!');

while(false !== ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
  // display field/column names as first row
  fputcsv($out, array_keys($row), ',', '"');
  $flag = true;
}
array_walk($row, 'cleanData');
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
626
  • 1,159
  • 2
  • 16
  • 27
  • 1
    Some reason that you can't use [`SELECT ... INTO OUTFILE`](http://dev.mysql.com/doc/en/select-into.html)? – eggyal Sep 26 '13 at 00:03

1 Answers1

0

It could be an issue with your delimiters. It works for me when only using the filename and array as parameters (aka. not specifying param 3 and 4).