fputcsv - Function gives Error. - php

I'm trying to export my data into a csv file and let the user to download it. I'm using fputcsv() function, but in the file, the data are written in a single cell instead of adjacent cells. I don't know what is the problem. Please help me. here is my code
session_start();
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename=report_'.time().'.csv;');
$data = $_SESSION['data'];
$file = fopen('php://output','w');
foreach($data as $i=>$value)
{
fputcsv($file, $value,";");
}
fclose($file);
and this is how the file looks like..

try like
$data = array (
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"');
$fp = fopen('php://output', 'w+');
header('Content-type: application/octet-stream');
header('Content-disposition: attachment; filename="data.csv"');
foreach($data as $line){
$val = explode(",",$line);
fputcsv($fp, $val);
}
fclose($fp);
or try may be according your data
foreach($data as $i=>$value)
{
fputcsv($file, $value);
}

Use , instead of ; for delimiter
Replace fputcsv($file, $value,";"); with fputcsv($file, $value, ","); and try
Example:
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename=report_'.time().'.csv;');
$data = array(array('one' => 1, 'two' => 2));
$file = fopen('php://output','w');
foreach($data as $i => $value)
{
//fputcsv($file, $value, ";");
fputcsv($file, $value, ",");
}
fclose($file);

Related

didn't download .csv in laravel (php)?

I am new in laravel, when I hit my code then it's given response in browser like
output:
ID,"Event Name"
1,"test event"
3,"test test 1"
please see my below code and guide me =>
$events = Events::all()->toArray();
$event_set = array();
//echo '<pre>'; print_r($events); die;
$i =0;
foreach ($events as $event)
{
$record['id'] = $event['id'];
$record['event_name'] = $event['event_name'];
$event_set[$i] = $record;
$i++;
}
//echo '<pre>'; print_r($event_set); die('test');
$filename = "events.csv";
$header = ['ID', 'Event Name'];
$export_data = $this->getDataCsv($event_set, $header);
return response($export_data)
->header('Content-Type','application/csv')
->header('Content-Disposition', 'attachment; filename="'.$filename.'"')
->header('Pragma','no-cache')
->header('Expires','0');
function getDataCsv($data, $headers, $delimiter = ',', $enclosure = '"') {
$filename = "php://temp";
$fp = fopen($filename, 'w');
fputcsv($fp, $headers, $delimiter, $enclosure);
if(count($data)>0){
foreach ($data as $key => $value) {
fputcsv($fp, $value, $delimiter, $enclosure);
}
}
rewind($fp);
$csvdata = fread($fp, 1048576);
fclose($fp);
return rtrim($csvdata, "\n");
}
please suggest me, what I doing wrong ?
use this function to generate and download CSV file
pass data as:
$data = [
['ID', 'Event Name', 'test event'], // this is going to be header for the csv file
[1, 'xyz', 'aadfas'],
[2, 'abc', 'jljljl'],
];
and call this function
public function arrayToCSVDonwload($data, $fileName = null, $delimiter = ",")
{
$fileName = $fileName ? $fileName . '.csv' : microtime(true) . ".csv";
header("Content-Type: application/csv");
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=$fileName");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
$output = fopen("php://output", "w");
foreach ($data as $row) {
fputcsv($output, $row, $delimiter);
}
fclose($output);
exit;
}

fputcsv appends 'null' at end of file

I am trying to export some data as csv using the following code but it appends an unwanted 'null' at file end.
$array = array();
$fileName = 'test.csv';
$array[0] = ['Name','Email'];
$array[1] = ['Test','test#email.com'];
$fileObj = new FileStream();
$fileObj->array_to_csv_download($array,$fileName);
array_to_csv_download code -
$f = fopen('php://memory', 'w');
foreach ($array as $line) {
$this -> logObj -> LogError(" CSV ".json_encode($line));
fputcsv($f, $line, $delimiter);
}
fseek($f, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');
fpassthru($f);
Output -
Name,Email
Test,test#email.com
null
Am I missing something?
How about generating CSV directly? Works for me.
header('Content-Type: application/csv');
foreach($array as $fields) {
echo implode(",", $fields)."\n";
}

Array to CSV to file

I'm creating a CSV from an array. The problem is that I dont want to download it but I want to save it to a folder in my server. This is my function
protected function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
header('Content-Type: application/csv; charset=utf-8');
header('Content-Disposition: attachement; filename="'.$filename.'";');
$f = fopen('php://output', 'w');
foreach ($array as $line) {
fputcsv($f, $line, $delimiter);
}
}
How can I make it so that it saves it to the server? Thanks!
Remove headers.
Use you server's file path in fopen handle.
$f = fopen('path of file on server ', 'w');

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();
}

write into csv file in php

I have to create and write into a csv file. Now I tried with the following code:
header('Content-type: application/octet-stream');
header('Content-disposition: attachment; filename="data.csv"');
$data = array (
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"');
$fp = fopen('php://output', 'w+');
foreach($data as $line){
$val = explode(",",$line);
fputcsv($fp, $val);
}
fclose($fp);
It gives me my source file code also in the csv file? How can I solve this?
Wrap it in <?php and ?> tags.
Change the first header to header('Content-type: text/csv');
header() needs to come after the array and fopen
try this:
$data = array (
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"');
$fp = fopen('php://output', 'w+');
header('Content-type: application/octet-stream');
header('Content-disposition: attachment; filename="data.csv"');
foreach($data as $line){
$val = explode(",",$line);
fputcsv($fp, $val);
}
fclose($fp);
Try this:
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$data = array (
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"');
$fp = fopen('php://output','w');
foreach ($data as $line) {
fputcsv($fp, array_map('utf8_decode',array_values($line)), ',', '"');
}
fclose($fp);

Categories