didn't download .csv in laravel (php)? - 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;
}

Related

Pull customer data into all columns in a csv file

This is my current code which pulls all data into a single column. I would like it
to pull data into its own column. Thanks for any help
<?php
include('codelibrary/inc/variables.php');
include("session.php");
$obj= new database_class();
$query = $obj->getAnyTableAllData($obj->getTable("var_customer")," and email != '' order by email ");
$filename = 'customer_email.csv';
$fp = fopen($filename, 'w');
foreach ($query as $k=>$v) {
$_csv_data= $v["email"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["first_name"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["business"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["phone_no"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["shipping_address"]. "\n";
fwrite( $fp, $_csv_data );
}
fclose($fp);
if(is_file($filename))
{
$size=filesize("$filename");
header("Content-type: application/csv");
header("Content-Length: $size");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);
exit;
}
else
{
echo "Invalid file!";
}
?>
This is my first post on here and I've found all the info here very informative. Thanks for all you do.
EDIT:
Here is the current code with the syntax error
<?php
include('codelibrary/inc/variables.php');
include("session.php");
$obj= new database_class();
$query = $obj->getAnyTableAllData($obj->getTable("var_customer")," and email != '' order by email ");
$filename = 'customer_email.csv';
$fp = fopen($filename, 'w');
# let's get keys into an order that you like
$fields = array('email','first_name','business','phone_no','shipping_address');
foreach ($query as $k=>$v) {
// put the fields for this row into an array
foreach ($fields as $field) {
$data[] = $v[$field];
}
fputcsv($fp, $data);
unset($data);
}
fclose($fp);
if(is_file($filename))
{
$size=filesize("$filename");
header("Content-type: application/csv");
header("Content-Length: $size");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);
exit;
}
else
{
echo "Invalid file!";
}
?>
For CSVs, instead of fwrite, you can use fputcsv, you just pass it an array of columns to insert in the row.
$array = array('column one contents', 'column two contents');
fputcsv($fp, $array);
I would suggest looking into fputcsv.
php manual
It looks like your code was looping through all the data, printing out the email. Then looping again and printing out the first_name... I haven't tested it, but this uses fputcsv to write the file - I changed only those parts of the code.
<?php
include('codelibrary/inc/variables.php');
include("session.php");
$obj= new database_class();
$query = $obj->getAnyTableAllData($obj->getTable("var_customer")," and email != '' order by email ");
$filename = 'customer_email.csv';
$fp = fopen($filename, 'w');
# let's get keys into an order that you like
$fields = array('email','first_name','business','phone_no','shipping_address');
foreach ($query as $k=>$v) {
// put the fields for this row into an array
foreach ($fields as $field) {
$data[] = $v[$field];
}
$lines[] = $data; // add the row of data to $lines
unset($data);
}
fputcsv($fp, $lines);
fclose($fp);
if(is_file($filename))
{
$size=filesize("$filename");
header("Content-type: application/csv");
header("Content-Length: $size");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);
exit;
}
else
{
echo "Invalid file!";
}
?>

create CSV in a different name if file already exists

i have been creating a CSV by using array of data, currently it returns an error if a CSV already exists in the same location.
therefore is there a possibility where i could let it create another in the same location.
example : if theres a csv called report.csv to create a new one with auto generated name like report(1).csv
code
$exportBaseDir = 'C:/Users/myflder';
$fileD = "report".csv";
$basePath = "$exportBaseDir/weeklyReport/$fileD";
$fp = fopen($basePath, 'w');
$header = array("XXX","XX","XX","XX","XX","XX","XX","XX");
fputcsv($fp, $header, ',');
foreach ($tables as $fields) {
fputcsv($fp, $fields,',');
}
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Transfer-Encoding: binary");
fclose($fp);
working example finally.. thank you for your ideas
$exportBaseDir = 'C:/Users/myflder';
$fileD = "report".csv";
$basePath = "$exportBaseDir/weeklyReport/$fileD";
if(file_exists($basePath) == false){
$fp = fopen($basePath, 'w');
$header = array("XXX","XX","XX","XX","XX","XX","XX","XX");
fputcsv($fp, $header, ',');
foreach ($tables as $fields) {
fputcsv($fp, $fields,',');
}
}
else{
$time_start = time();
$exportBaseDir = 'C:/Users/myflder';
$fileD = "report"."#".$time_start.".csv";
$basePath = "$exportBaseDir/weeklyReport/$fileD";
$fp = fopen($basePath, 'w');
$header = array("XXX","XX","XX","XX","XX","XX","XX","XX");
fputcsv($fp, $header, ',');
foreach ($tables as $fields) {
fputcsv($fp, $fields,',');
}
}

fputcsv - Function gives Error.

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

Issue on opening, editing and downloading a .csv file on PHP

I want to open a csv file named csv.csv with PHP, then add new rows in this file, and finally download the news csv.
The content of csc.csv is:
name, town
name1, town1
name2, town2
name3, town3
name4, town4
and I want to add these rows:
name5, town5
name6, town6
I made this PHP code but it doesn't work:
<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$file = fopen("csv.csv","r");
$list = array();
while(! feof($file))
{
$list[] = array(print_r(fgetcsv($file)));
}
fclose($file);
$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');
outputCSV($list);
function outputCSV($list) {
$output = fopen("php://output", "w");
foreach ($list as $row) {
fputcsv($output, $row);
}
fclose($output);
}
?>
Here is your working code.
<?php
$file = fopen("csv.csv","a+");
$list = array();
$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');
foreach ($list as $fields) {
fputcsv($file, $fields,',');
}
fclose($file);
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=csv_".time().".csv");
header("Pragma: no-cache");
header("Expires: 0");
?>
UPDATE 1 :
for creating new file without editing existing one.
<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$file = fopen("csv.csv","r");
$list = array();
while(! feof($file))
{
$list[] = (fgetcsv($file));
}
fclose($file);
$list[] = array('name5', 'town5');
$list[] = array('name6', 'town6');
$list = array_filter($list);
outputCSV($list);
function outputCSV($list) {
$output = fopen("php://output", "w");
foreach ($list as $row) {
fputcsv($output, $row);
}
fclose($output);
}
?>

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

Categories