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);
Related
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
I'm currently trying to make a file download in the user's browser but have so far been unable to make it happen.
I've looked at other answers on stackoverflow.com and so far haven't found anything that has solved my problem.
My process is as follows:
I create the filename and filepath, then set headers:
$date = new DateTime();
$currentDateTime = $date->format("Y-m-d H:i:s");
$filename = "{$name}_{$currentDateTime}.csv";
$filepath = $rootfull . "/{$filename}";
// Set headers
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $filepath . '"');
header('Content-Length: ' . filesize($filepath));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
I then create the file and start writing to it:
// Write header
fputcsv($output, $header);
fputcsv($output, array()); // Empty line
// Write column names
$column_headers = array_keys(array_flip($columns));
foreach ($data as $row)
{
fputcsv($output, $row);
}
echo readfile($filepath);
die();
The file gets generated and written to the specified location (in this case /var/www/<project>/<filename>.csv without any indication to the user that anything has happened. No download dialog, nothing.
If anyone can spot a problem with my code or my process, please point it out and preferably suggest a better/alternative way of doing it, any help at all is welcome at this point.
If no benefit (poor mans cache) to writing to disk then maybe something like this writing to buffer:
<?php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="dump_' . date('Ymd') . '.csv"');
header("Pragma: no-cache");
header("Expires: 0");
$this->outputCSV($results);
exit(); //->
public function outputCSV($data, $useKeysForHeaderRow = true)
{
if ($useKeysForHeaderRow) {
array_unshift($data, array_keys(reset($data)));
}
$outputBuffer = fopen("php://output", 'w');
foreach($data as $v) {
fputcsv($outputBuffer, $v);
}
fclose($outputBuffer);
}
?>
I have the following function that takes an array of results from a database query. I populate the array as I loop through the query results. At the same time I create an html table. After outputting the html table I call the function download_csv($csvArray) but no downloading of the CSV happens, It just displays the contents of the the array as if I did a var_dump on the array. I can confirm that the contents of the array are correct.
Note: this is being done on an external web page not from the admin area.
Is there some wordpress function that needs to be called to allow the download or am I missing something?
function download_csv($csvArray) {
$file_name = 'report.csv';
//output headers so that the file is downloaded rather than displayed
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=$file_name");
//Disable caching - HTTP 1.1
header("Cache-Control: no-cache, no-store, must-revalidate");
//Disable caching - HTTP 1.0
header("Pragma: no-cache");
//Disable caching - Proxies
header("Expires: 0");
//Start the ouput
$output = fopen("php://output", "w");
//Then loop through the rows
foreach ($csvArray as $fields) {
fputcsv($output, $fields);
}
//Close the stream off
fclose($output);
die();
}
Following Code will help you to convert Array to CSV and Make it to automatically download Change the die(); function to exit(); And Use Implode function. It will work.
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename=sample.csv');
header('Pragma: no-cache');
header('Expires: 0');
$fp = fopen('php://output', 'w');
//ex: $list={...};
foreach ($list as $fields)
{
fputcsv($fp,implode($fields, ','));
}
fclose($fp);
exit();
I have a 3rd party source from where I am getting "csv" file. I wrote it inside a quote because it says it's a csv file but basically it's not.
So I am taking that main source file then reading and putting the data in a "PROPER" csv file.
The read and write is fine but the problem is when it saves the properly quoted data is writing on the script file itself.For example if the my php file name is "fixcsv.php" then I am getting the downloadable file as "fixcsv.php".
My code
$headings = array('HID');
$handle = fopen("MonC1.csv", "r");
$data = fgetcsv($handle, 0, ";",'"');
$fh = fopen('php://output', 'w');
ob_start();
fputcsv($fh, $headings);
// Loop over the * to export
if (! empty($data)) {
foreach ($data as $item) {
// echo $item;
fputcsv($fh, array($item));
}
}
$string = ob_get_clean();
$filename = 'csv_' . date('Ymd') .'_' . date('His');
// Output CSV-specific headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment filename=\"$filename.csv\";" );
header("Content-Transfer-Encoding: binary");
exit($string);
Any help is highly appreciated. Thanks in advance.
Your Content-Disposition has a semi-colon in the wrong place (per the spec). Should be:
header("Content-Disposition: attachment; filename=\"$filename.csv\" );
There is a download in CSV feature in my current CodeIgniter project. When a user click the link, it will download a file in CSV. The downloaded CSV file's filename is incorrect once the provided filename in the code has a question mark character. To make things clear, below is the code.
public function download($role = NULL, $id = 0, $eid = 0) {
$this->load->helper('download');
$list = $this->respondent->get_respondents($eid);
$questions = $this->respondent->get_all_questions($eid);
$fp = fopen('php://output', 'w');
$fields = array(
'Timestamp',
'First Name',
'Middle Name',
'Last Name',
);
$fields = array_merge($fields, $questions);
fputcsv($fp, $fields);
foreach ($list as $respondent) {
$respondent_data = array(
$respondent->since,
$respondent->first_name,
$respondent->middle_name,
$respondent->last_name,
);
$query = $this->respondent->get_responses($respondent->rid);
foreach($query as $response) {
array_push($respondent_data, $response->answer, $response->duration);
}
fputcsv($fp, $respondent_data);
}
$data = file_get_contents('php://output');
$name = $this->respondent->get_experiment($respondent->eid)->title.'.csv';
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Disposition: attachment; filename="'.basename($name).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
exit();
force_download($name, $data);
fclose($fp);
}
In the line header('Content-Disposition: attachment; filename="'.basename($name).'"');, once the $name has a question mark character, downloading the file in Firefox or Chrome browser can't interpret it correctly. Rather than a question mark character, the generated character is an underscore or hyphen, respectively. However, when Safari is used to download, the filename is just fine. Is the problem in the code or the browsers?
What I meant in my comment is this.
str_replace('?', '_', $name); //when saving file on the server
This way there is no limit for users simply every question mark is replaced with _, I guess no big deal.
The part about FF and GCH I can not answer.