Non-ascii characters in fputcsv - php

So I have a simple script that writes some data to a CSV-file. The file contains a few non-ascii characters (norwegian characters) which are not displayed correctly in when opened in Excel. However they are displayed correctly in OpenOffice. Does anyone know how to fix this?
$fp = fopen('php://output', 'w');
if(!$fp)
{
echo "Could not write CSV-file"; die;
}
$filename = sprintf('%s_export_%s.csv', $marketplace, date('Y_m_d_H_i_s'));
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Pragma: no-cache');
header('Expires: 0');
foreach($collection as $i => $item)
{
$result = array();
$result[] = $item->getData('email');
$result[] = $item->getData('firstname');
$result[] = $item->getData('lastname');
fputcsv($fp,$result, ";");
}
flush();
fclose($fp);

Windows needs a BOM to know that a file is UTF-8 and open it correctly.
Before your foreach, add the following line:
fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));

Related

Why my CSV file was start filling from the 2nd line?

I am exporting MySQL data successfully to a csv file. But in the csv file first line was empty and data starts from 2nd line. Below is my code.
$delimiter = ";";
$generated_date = date("Y-m-d-H-i-s");
$filename = 'order_detail_report'.$generated_date.".csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');
$output = fopen('php://output', 'w+');
fputcsv($output, array('Order Type','Order Number','EAN','Article #'),$delimiter);
sql query
<?php
$lineData = array();
$query = "my select query";
$res = mysqli_query($mysqliConn,$query);
while($result= mysqli_fetch_assoc($res))
{
$lineData[] = $result;
fputcsv($output, $lineData, $delimiter);
unset($lineData);
}
Data was exporting successfully to csv but it was starting from 2nd line, any help would be greatly appreciated.
EDIT
<?php
//header info for browser
$delimiter = ";";
$generated_date = date("Y-m-d-H-i-s");
$filename = 'order_detail_report'.$generated_date.".csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');
$output = fopen('php://output', 'w');
fputcsv($output, array('Order Type','Order Number','EAN','Article #','Title','Amazon Price','ERP Price','Requested Quantity','Dispatch Quantity','Rejected Quantity','Cancelled Quantity','Delivery Date','Status','EDD','LDD','Dispatch Center','Order Received','Price Status','Country'),$delimiter);
?>
I just removed all my mysql related query and only using the above one.

Create CSV and Force to Download

I want write a CSV and force to Download it automatically. Bit it only displays the file. My code:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
// open to write
$fp = fopen($fileName, 'w');
// MS-Excel BOM:
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
// write columns
foreach ($columnNames as $fields) {
fputcsv($fp, $fields, ';');
}
$exportData = array (
array($value1, $value2, $value3)
);
foreach ($exportData as $fields) {
fputcsv($fp, $fields, ';');
}
fclose($fp);
I have tried for hours. Nothing do the job. It will only be displayd.
You can try adding the file to a zip file and asking your visitors to change their settings so that zip files are automatically downloaded.
https://www.tipsandtricks-hq.com/forum/topic/force-a-file-to-download-instead-of-showing-up-in-the-browser

Issues with exporting a csv file

I'm creating a function that, when you click on a button, submits datas to a this function and in return, creates a .csv file and makes the browser download it. I followed the huge amount of tutorials that can be found online, but maybe I'm mixing up things:
header("Content-Type: application/x-excel");
header("Content-disposition: attachment; filename=export".date('d-m-Y') .".csv");
header('Expires : 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
$list = array
(
"Peter,Griffin,Oslo,Norway",
"Glenn,Quagmire,Oslo,Norway",
);
$file = fopen("contacts.csv","w");
foreach ($list as $line) {
fputcsv($file,explode(',',$line));
}
die($file);
readfile($file);
Just keep in mind that these aren't my real datas, I just want to set everything up before continuing, because I have 50 lines of an array to handle.
With this code, If I keep die($file), the file gets downloaded but is empty. If I remove it, my browser tells me that the website is unavailable.
What am I missing?
try this
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
"Peter,Griffin,Oslo,Norway",
"Glenn,Quagmire,Oslo,Norway",
);
$fp = fopen('php://output', 'w');
foreach ( $data as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);

How to fix error font UTF8 in file csv when export file csv in php

I export csv in php as:
$fp = fopen($filename, 'w');
foreach ($list as $fields) {
if(!empty($fields))
fputcsv($fp, $fields);
else
fputcsv($fp, ' ');
}
$fp = chr(255).chr(254).mb_convert_encoding($fp,"UTF-16LE","UTF-8");
fclose($fp);
When i open csv, font UTF_8 is error.
Ex: 防本部コー show in file csv: æ¶ˆé˜²æœ¬éƒ¨ă‚³ăƒ¼ăƒ‰
Can I help you? Thanks
This has been discussed here:
How can I output a UTF-8 CSV in PHP that Excel will read properly?
You might also want to check your CSV in an alternative text editor to rule out the editor.
$fp is a pointer resource to a file. It is not a string, you cannot do this:
$fp = chr(255).chr(254).mb_convert_encoding($fp,"UTF-16LE","UTF-8");
To write UTF-16 data to the file, you need to convert it before writing it, not after the fact:
$fp = fopen($filename, 'w');
fwrite($fp, chr(255).chr(254));
foreach ($list as $fields) {
foreach ($fields as &$field) {
$field = mb_convert_encoding($field, 'UTF-16LE', 'UTF-8');
}
fputcsv($fp, $fields);
}
fclose($fp);
Don't know if this actually outputs the data you need, but it fixes the obvious error.
Try this function will work:
public static function exportCSVFile($data = array(), $headers = array(), $delimiter = ",", $csvfilename = "CSVFile") {
ob_clean();
ob_start();
$csvfilename = $csvfilename . "_" . date("Y_m_d_h_i_s") . ".csv";
$file_handler = fopen("php://output", 'w');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/csv");
//header( "Content-Type: application/csv;charset=utf-8" );
header("Content-Disposition: attachment;filename={$csvfilename}");
header("Content-Transfer-Encoding: binary");
foreach ($data as $fields) {
$_str = implode($delimiter, $fields);
$fields = explode($delimiter, utf8_decode($_str));
fputcsv($file_handler, $fields, $delimiter, $enclosure = '"');
}
fclose($file_handler);
ob_flush();
exit();
}

php://output results in empty file

I have a Wordpress theme template file in use by a page. The template queries the db for an array and then attempts to output the result to a csv file. No output to the browser is expected. Here is code:
/***
* Output an array to a CSV file
*/
function download_csv_results($results, $name = NULL)
{
if( ! $name)
{
$name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
}
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='. $name);
header('Pragma: no-cache');
header("Expires: 0");
$outstream = fopen("php://output", "w");
foreach($results as $result)
{
fputcsv($outstream, $result);
}
fclose($outstream);
}
The file is written to the user's downloads directory as expected, but it is empty. I've debugged to verify there is a result of 117 elements. The loop above is executing. It's as though the output buffer is not being flushed or is being cleared by Wordpress.
Could you try to use :
$outstream = fopen("php://output", "a");
instead of :
$outstream = fopen("php://output", "w");

Categories