I have this code which I use to export a query in CSV, the problem is that, if I open this with Excel the russian characters won't display, but if I open it with numbers(Mac) they display.
Now, I can't get what's wrong with this. I've added some lines I saw on internet and nothing..
<?php
/*
* PHP code to export MySQL data to CSV
* http://salman-w.blogspot.com/2009/07/export-mysql-data-to-csv-using-php.html
*
* Sends the result of a MySQL query as a CSV file for download
*/
/*
* establish database connection
*/
$conn = mysql_connect('', '', '') or die(mysql_error());
mysql_select_db('', $conn) or die(mysql_error($conn));
mysql_query("SET NAMES UTF8");
/*
* execute sql query
*/
$query = sprintf('SELECT fields FROM table');
$result = mysql_query($query, $conn) or die(mysql_error($conn));
/*
* send response headers to the browser
* following headers instruct the browser to treat the data as a csv file called export.csv
*/
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment;filename=hostess.csv');
/*
* output header row (if atleast one row exists)
*/
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array_keys($row));
}
/*
* output data rows (if atleast one row exists)
*/
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
/*
* echo the input array as csv data maintaining consistency with most CSV implementations
* - uses double-quotes as enclosure when necessary
* - uses double double-quotes to escape double-quotes
* - uses CRLF as a line separator
*/
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
?>
The script was not created for UTF-8 encoded data. It dumps the data almost as-is. The resulting CSV file will contain (probably) valid UTF-8 encoded data but no signature. In the absence of signature, some software will use heuristics to detect the encoding; others, like Excel, won't.
You must tell excel to treat the file as UTF-8 encoded. For this, you need to import the file in Excel (Data > Get External Data > From Text) instead of opening it directly (double-clicking or using File > Open). Inside the Text Import Wizard, choose the appropriate encoding and Excel should import the data correctly. See screenshots below.
Alternately, you could try adding the UTF-8 signature manually. I haven't tried it myself.
// ...
header('Content-Disposition: attachment;filename=hostess.csv');
echo "\xEF\xBB\xBF";
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With