Force Download CSV File
Put this code below your loop.
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="pedidos.csv"');
echo $shtml;
How did you find out the content type application/force-download? I've never heard of it. The proper MIME type for CSV is text/csv
You can find more examples how to use header function in php manual
You need also display $shtml
you didn't do it in your code.
Create CSV and force download of file
Charlie, this is a sample way to create and force download to csv file. Try to implement this in your code:
<?php
$filename = 'test';
$filepath = $_SERVER["DOCUMENT_ROOT"] . $filename.'.csv';
$output = fopen($filepath, 'w+');
fputcsv($output, array("Number", "Description", "test"));
fputcsv($output, array("100", "testDescription", "10"));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
header('Content-Length: ' . filesize($filepath));
echo readfile($filepath);
Forcing to download a file using PHP
.htaccess Solution
To brute force all CSV files on your server to download, add in your .htaccess file:
AddType application/octet-stream csv
PHP Solution
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");
Force the browser to download file as CSV from url
Trick here is to convert your data into blob and simulate a click event on an anchor tag with blob url.
var blob = new Blob([content]);
create an click event
var evnt = new Event('click');
then create an anchor tag as follows and dispatch event
$("<a>", {
download: filename,
href: webkitURL.createObjectURL(blob)
}).get(0).dispatchEvent(evnt);
Here is a function
var download = function(filename, content) {
var blob = new Blob([content]);
var evnt = new Event('click');
$("<a>", {
download: filename,
href: webkitURL.createObjectURL(blob)
}).get(0).dispatchEvent(evnt);
};
Use the above download function.
USAGE: call the function download with two parameters filename
and content
openFile(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(data) {
if (this.readyState == 4 && this.status == 200) {
download('file.csv', data);
}
};
xhttp.open("GET", url, true);
xhttp.send();
//window.open(url, '_blank')
}
Download csv file as response on AJAX request
In modern browsers, you can prompt a download by creating a Blob with your file contents (in your case received by Ajax), creating a URL for it, and using the download
attribute:
const saveData = (function () {
const a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
const blob = new Blob([data], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
const data = 'a,b,c\n5,6,7',
fileName = "my-csv.csv";
saveData(data, fileName);
JSFiddle
If your Ajax endpoint URL has the proper headers (or possibly even if it isn't as long as you use the download
attribute), you can forego the Blob and Ajax and just add the URL to the link with the download attribute. Adapting @pritesh's code,
const saveData = (function () {
const a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (url, fileName) {
a.href = url;
a.download = fileName;
a.click();
};
}());
const url = 'http://www.sample-videos.com/csv/Sample-Spreadsheet-10-rows.csv', // Replace with your own URL: window.location + "/downloadUserAction?draw=3&search%5Bvalue%5D=NLP_SEARCH&order%5B0%5D%5Bcolumn%5D=6&order%5B0%5D%5Bdir%5D=desc"
fileName = "my-csv.csv";
saveData(url, fileName);
JSFiddle
Automatically downloading .csv in Selenium
There are several kinds of csv
applications. We can't know what will work for the specific site you are working with.
I have all these preferences set and so far it works for me in all the cases
op.set_preference("browser.download.dir", downloadsPath)
op.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/csv,application/excel,application/vnd.ms-excel,application/vnd.msexcel,text/anytext,text/comma-separated-values,text/csv,text/plain,text/x-csv,application/x-csv,text/x-comma-separated-values,text/tab-separated-values,data:text/csv")
op.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/xml,text/plain,text/xml,image/jpeg,application/octet-stream,data:text/csv")
op.set_preference("browser.download.folderList",2)
op.set_preference("browser.download.manager.showWhenStarting",False)
op.set_preference("browser.helperApps.neverAsk.openFile","application/csv,application/excel,application/vnd.ms-excel,application/vnd.msexcel,text/anytext,text/comma-separated-values,text/csv,text/plain,text/x-csv,application/x-csv,text/x-comma-separated-values,text/tab-separated-values,data:text/csv")
op.set_preference("browser.helperApps.neverAsk.openFile","application/xml,text/plain,text/xml,image/jpeg,application/octet-stream,data:text/csv")
op.set_preference("browser.helperApps.alwaysAsk.force", False)
op.set_preference("browser.download.useDownloadDir", True)
op.set_preference("dom.file.createInChild", True)
downloadsPath
here is a path to Downloads folder
Related Topics
Unserialize PHP Data in Python
PHP - How to Get Shell Errors Echoed Out to Screen
PHP Session Variables Not Preserved with Ajax
PHP - Syntax Error, Unexpected T_Constant_Encapsed_String
PHP Readfile() Adding Extra Bytes to Downloaded File
Laravel Form Methods VS Traditional Coding
Adding Additional Persist Calls to Preupdate Call in Symfony 2.1
Codeigniter "Flashdata" Doesn't Work
Easiest Way to Grab Filesize of Remote File in PHP
Best Method for Converting a PHP Array to JavaScript
How to Convert a Huge Integer to Hex in PHP
Do I Need to Escape My Variables If I Use MySQLi Prepared Statements
How to Convert an Iso8601 Date to Another Format in PHP
Php: Remote Function Call and Returning the Result
Convert Unicode to HTML Entities Hex
PHP Xml Inserting Element After (Or Before) Another Element