Generate csv file using laravel - php

I searched in google to generate the csv file from laravel and i have found the following code:
public function download(){
$headers = [
'Cache-Control' => 'must-revalidate, post-check=0, pre- check=0'
, 'Content-type' => 'text/csv'
, 'Content-Disposition' => 'attachment; filename=galleries.csv'
, 'Expires' => '0'
, 'Pragma' => 'public'
];
$list = User::all()->toArray();
# add headers for each column in the CSV download
array_unshift($list, array_keys($list[0]));
$callback = function() use ($list)
{
$FH = fopen('php://output', 'w');
foreach ($list as $row) {
fputcsv($FH, $row);
}
fclose($FH);
};
return Response::stream($callback, 200, $headers);
}
In the above code, i didn't understand
$callback = function() use ($list){...}
will someone please explain me?

Save yourself a world of trouble and use this library: http://www.maatwebsite.nl/laravel-excel/docs
It can convert your data to csv, excel and all other sorts of goodies. It's especially good with larger datasets.
Cause it's all fun and games when you open your csv in the same program on the same OS. But as soon as your client uses Libre, Open or just Office op MS or Mac your world will go to new depths of hell in multiple layers.
This library standardises csv for as far as possible and you will love it.

I've recently discovered the 'league/csv' package - have written a S.O post about my usage (a simple example) here: CSV export in laravel 5 controller

Related

Laravel: Can't download the generated file

I have a function where I generates excel (.csv) file. Everything is working except download.
So my idea was to download the file automatically in the browser after generating the csv file. When the file was generated we store it in the public folder.
So when I call my function , the function is opening the url: http://127.0.0.1:8000/project/tools/export/exportData and displaying the file instead of downloading it. So for this I need your help! Thank you in advance.
My codes :
public function exportData() {
$size=sizeof($arr);
for($i=0; $i<$size; $i++)
{
fputcsv($fh,$arr[$i]);
}
fclose($fh);
$file="Export.csv";
$headers = array(
'Content-Type: text/csv',
);
return response()->download($file, 'Export.csv', $headers);
}
You can add the content-disposition to your headers to indicate how to handle file:
$headers = [
'Content-type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="filename.csv"',
];
To display the file in the browser instead of downloading it, you would exchange attachment for inline.

Guzzle 6 download file

Need help using Guzzle 6 for downloading a file from a rest API. I don't want the file to be saved locally but downloaded from web browser. Code so far below, but believe I am missing something?
<?php
//code for Guzzle etc removed
$responsesfile = $client->request('GET', 'documents/1234/content',
[
'headers' => [
'Cache-Control' => 'no-cache',
'Content-Type' => 'application/pdf',
'Content-Type' => 'Content-Disposition: attachment; filename="test"'
]
]
);
return $responsesfile;
?>
Just do research inside Guzzle's docs, for example here
Pass a string to specify the path to a file that will store the contents of the response body:
$client->request('GET', '/stream/20', ['sink' => '/path/to/file']);
Pass a resource returned from fopen() to write the response to a PHP stream:
$resource = fopen('/path/to/file', 'w');
$client->request('GET', '/stream/20', ['sink' => $resource]);
Pass a Psr\Http\Message\StreamInterface object to stream the response body to an open PSR-7 stream.
$resource = fopen('/path/to/file', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$client->request('GET', '/stream/20', ['save_to' => $stream]);
stream_for is deprecated in version 7.2. You can use
GuzzleHttp\Psr7\Utils::streamFor($resource) instead.
First of all, Content-Type header only makes sense when you send something (POST/PUT), but not for GET requests.
Secondly, what is your issue? Guzzle by default does not store the response body (file) somewhere, so you can work with it inside your app, like $responsesfile->getBody().

Laravel Excel download not working

The problem is the same as described here Laravel Excel Download using Controller
But I just can not believe that there is no method to deal with Excel downloads in Laravel without using another resource. I was already able handle the instant downloads in controller with response() for PDFs.
Mabybe the headers are wrong? My code:
public function getFile($file) {
$path = storage_path('app/excel/exports/' . $file);
$headers = array('Content-Type' => File::mimeType($path));
return response()->download($path, $file, $headers);
}
So the excel file is created and saved correctly in my storage folder (happens before the code above). Then I use an axios.get method to download the file with the function above.
Headers I am getting:
Accept-Ranges:bytes
Cache-Control:public
Connection:keep-alive
Content-Disposition:attachment; filename="test_file.xlsx"
Content-Length:7066
Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
But whatever I do or try to change the download just won't start.
You can try with these two headers.
return response()->download($path, $file, [
'Content-Type' => 'application/vnd.ms-excel',
'Content-Disposition' => "attachment; filename='Report.xls'"
]);
Thanks,
I manged to solve it.
It seems to be not possible to solve this with a simple axios.get request to the route. Instead I needed to open the route directly with a link.
Did not work with:
HTML
<button #click="downloadExcel()">Download Table as Excel File</button>
downloadExcel() {
axios.get('/customers/export');
}
Simple solution (instead of just using axios.get):
<a :href="/customers/export"><button>Download Table as Excel File</button></a>
So it would also be possible to open the route after the axios request with:
downloadExcel() {
let newWindow = window.open();
axios.get('/customers/export')
.then(response => {
newWindow.location = 'http://' + window.location.hostname + '/customers/export';
});
}

How to download a file from URL without showing the full path in laravel?

Download link:-
<a href='"+ downloadlink + '/attachment-download/' + $('#employee_ID').val()+'/'+ res[i].file_name +"'>
Route:-
Route::get('/attachment-download/{id}/{filename}', array(
'uses' => 'AttachmentsController#getDownloadAttachments'
));
Attachment Controller:-
public function getDownloadAttachments($id,$filename){
$file="./img/user-icon.png";
$resource = \Employee::WhereCompany()->findOrfail($id);
$path = $this->attachmentsList($resource);
foreach($path as $index => $attachment){
if ($filename == $attachment['file_name']) {
$filePath = $attachment['url'];
}
}
//return \Response::download($file);
return \Response::download($filePath);
}
File URL Output:-
https://zetpayroll.s3.ap-south-1.amazonaws.com/employees/81/Screenshot%20from%202017-04-26%2015%3A07%3A45.png?X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAI57OFN3HPCBPQZIQ%2F20170612%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20170612T144818Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3600&X-Amz-Signature=59ecc4d11b7ed71bd336531bd7f4ab7c84da6b7424878d6487679c97a8c52ca7
In this, if try to download the file by using a static path like
$file="./img/user-icon.png";
return \Response::download($file);
it is downloaded fine. But not possible to downloading file from AWS URL, Please help me how to down file automatically using URL. Or How to get Path from URL in laravel or PHP.
Thank you.
Using the above function all the files are being downloaded. But while trying to open the files, text, pdf, ... files open (.text, .csv, .pdf..) without problem, but images don't.
$fileContent = file_get_contents($filePath);
$response = response($fileContent, 200, [
'Content-Type' => 'application/json',
'Content-Disposition' => 'attachment; filename="'.$filename.'"',
]);
return $response;

How to download a file with RESTFUL cakePHP 2.3

I am using CakePHP 2.3 and I have two apps on 2 different servers. I am required to download a file from the first server using REST. I have made my applications RestFul and have configured the routes. I am able to post, get, put and delete but I cannot get it done to download the file.
Below is a sample code for a get
public function view($id) {
$object = $this->Imodel->find('first', array('conditions' => array('Imodel.id' => $id), 'contain' => array()));
$this->set(array(
'object' => $object,
'_serialize' => array('object')
));
}
I would appreciate any help to download a file with REST, complying with the Restful architecture that I already have in place.
Edit
After some time, I finally got it to work. In case someone else runs into the same problem, the whole thing was about understanding cakePHP HttpSocket better.
So first on the server where the webservice is registered (where we download the file from), below is my function; its response is a file as explained (here)
public function getpdffile($id = NULL){
$filepath = APP. 'Files/file.pdf'; //path to the file of interest
$this->response->file($filepath);
return $this->response;
}
Since the file was not public (not in webroot), i had to use MediaView. Then after setting this, I'd retrieve it for download using HttpSocket as shown below:
public function download($id = NULL, $fileMine = 'pdf', $fileName = 'file', $download = TRUE){
$httpSocket = new HttpSocket();
$filepath = APP. 'Files/myfile.pdf';
$file = fopen($filepath, 'w');
$httpSocket->setContentResource($file);
$link = MAIN_SERVER."rest_models/getpdffile/".$id.".json";
$httpSocket->get($link);
fclose($file);
$this->response->file($filepath);
return $this->response;
}
What I did there was copy the file to the App folder of my server and render it in a view.
I hope it helps someone :-)
On the server which call the file to download :
$file = file_get_contents(urlwhereyoudownload) ;
And on the server where webservice is register :
header('Content-type: $mimetypeoffile');
header('Content-Disposition: attachment; filename=".$fileName."');
readfile("$pathtofile");exit;

Categories