Don't write csv file's manually. Use the built in function.
e.g. http://uk3.php.net/manual/en/function.fputcsv.php
<?php
$delimiter = ',';
$enclosure = '"';
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields, $delimiter, $enclosure);
}
fclose($fp);
?>
The above code will create a file called file.csv
with your data on it. If you then want to send this file to the user as a CSV file, you can do this:
<?php
// Send the generated csv file to the browser as a download
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile('file.csv');
?>
Alternatively, you can send the CSV file to download directly without creating the file on server like this:
<?php
// mini-config
$delimiter = ',';
// Your data
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
// Send headers
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
// Output csv data
foreach ($list as $row) {
echo implode($delimiter, $row) . "\r\n";
}
?>
Hope this helps.