I had created a website using php. In that website,I want to create a report like thing,which involves transferring details from one table to an excel sheet which is downloadable.Is there any way to do this work? Please help me to find the solution.
Thank you.
You can fetch all rows from the database and use fputcsv function to put it as csv
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=export.csv");
header("Content-Transfer-Encoding: binary");
$csvHandler = fopen("php://output", 'w');
while ($row = mysql_fetch_array ($res))
{
fputcsv($csvHandler, $row);
}
You can use PHPExcel for generating data
and a simple function for file download:
function show_download($data, $name, $type = "unknown/unknown") {
header('Content-Type: ' . $type);
header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Content-Disposition: attachment; filename="' . $name . '"');
header('Content-Length: ' . strlen($data));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
print $data;
exit();
}
You can create a script that exports a CSV file like this :
header('Content-type: text/csv');
header("Content-Disposition: attachment; filename=clients_" . date("Ymd") . ".csv");
//Open PHP output stream
$fd = fopen('php://output', 'w');
$tab = array();
//get your results from your database
foreach ($results as $res)
$tab[] = array($res->Client_Name, $res->Client_Email);
foreach ($tab as $val)
fputcsv($fd, $val);
fclose($fd);
Related
I try to force download a pdf file from php that are in server...but all the file that i download only 1kb size.It not the same with actual size do i need to declare file size before download?
<?php
$path = "C:\Users\omamu02\Desktop\TESTPRINT" ;
$file = "NMT PRV PHG 370 2017.pdf";
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-disposition: attachment; filename= $file"); //Tell the filename to the browser
header("Content-type: application/force-download");//Get and show report format
header("Content-Transfer-Encoding: binary");
header("Accept-Ranges: bytes");
readfile($path); //Read and stream the file
get_curret_user();
error_reporting(0);
?>
First of all, you should fix your filename= $file header. Wrap your $file variable with a ' chars at least. Also, you don't need the closing tag in the end of the PHP file.
And I'm not sure about your headers, so I suggest you try the function below, it's quite common for any type of data and already contains some bugfixes and workarounds:
function download_file($file_path, $file_name = null, $file_type = 'application/octet-stream')
{
if ($file_name === null)
{
$file_name = basename($file_path);
}
if (file_exists($file_path))
{
#set_time_limit(0);
header('Content-Description: File Transfer');
header('Content-Type: ' . $file_type);
header('Content-Disposition: attachment; filename="' . str_replace('"', "'", $file_name) . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
}
exit;
}
when i send a csv file to the browser using header('Content-Disposition: attachment filename="xyz.cs" '); the file named as export.php (filename of the php-script) instead of xyz.csv
public function sendCSV($arrBody, $arrHeadings)
{
$fh = fopen('php://output', 'w');
ob_start();
fputcsv($fh, $arrHeadings);
if (! empty($arrBody)) {
foreach ($arrBody as $line) {
fputcsv($fh, $line);
}
}
$strBuffer = ob_get_clean();
$strFile = 'csv_' . date('Ymd') . '-' . uniqid() . '_export.csv';
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=\"$strFile\";" );
header("Content-Transfer-Encoding: binary");
exit($strBuffer);
}
I am making a webpage in which I have to insert in a JSON variable ($grav which contains all the raw data from JSON) a line break or a tab in 3 given situations. After that I force the download of the data as a xls file. Everything is working except the "preg_replace" part. It finds the delimiter, but instead of inserting a "\n" or "\t" it only inserts a white space, according to the xls file downloaded (the data is all in one cell instead of in multiple columns and lines (that is why I need line breaks and tabs).
$grav='"title":[{"field1":,"field3":,{"field4"}';
$grav = preg_replace("/\},\{/", "},\n{", $grav);
$grav = preg_replace("/\[\{/", "\n[{", $grav);
$grav = preg_replace("/,\"/", ",\"\t", $grav);
header("Content-Description: File Transfer");
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="data_ '. date("Ymd") . '_' . $id . '.xls"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("Content-Type: application/force-download");
header("Content-Type: application/download");
echo $grav;
How can I fix this?
you are trying to break a json code into 3 line?. any how i will give a idea to solve this problem using array . try to convert using json. it may helps you
<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');// i used associate array which is similar to json data
reset($fruit);
while (list($key, $val) = each($fruit)) {
$grav .= $key."=>". $val."<br>";// brakes the line into 3
}
header("Content-Description: File Transfer");
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="data_ '. date("Ymd") . '_' . $id . '.xls"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("Content-Type: application/force-download");
header("Content-Type: application/download");
echo $grav;
?>
Regarding downloading files and defining the headers, I am having trouble assigning a dynamic filename to my files. When using the code below :
header("Content-Disposition: attachment; filename=test.csv");
A test.csv file is generated for download. However if I use this:
header('Content-Disposition: attachment; filename=' . $filename . '.csv');
It generates a .php file instead. Using this method also doesn't pass the Content-Disposition or filename to the header.
Full code:
session_start();
$file =$_SESSION['csvf'];
$filename = $file."_".date("Y-m-d_H-i",time());
header ( "Content-type: text/csv" );
header("Content-Disposition: attachment; filename=test.csv");
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
print($file);
exit ();
What is the correct syntax?
EDIT
Working Code after suggestions
session_start ();
$file = $_SESSION ['csvf'];
$filename =date ( "Y-m-d_H-i", time () );
header ( "Content-type: text/csv" );
header ( "Content-Disposition: attachment; filename=".$filename );
header ( 'Expires: 0' );
header ( 'Cache-Control: must-revalidate' );
header ( 'Pragma: public' );
header ( 'Content-Length: ' . filesize ( $file ) );
print ($file) ;
exit ();
I don't see the path to example.csv specified on your code, you need to give the full path to $file, i.e.:
$mySession = $_SESSION['csvf'];
//since $_SESSION['csvf'] contains the actual data you cannot use it for filename
$filename = date("Y-m-d_H-i",time()).".csv";
//write $mySession contents to file. Make sure this folder is writable
file_put_contents("/home/site/csvfolder/$filename", $mySession);
$file = "/home/site/csvfolder/$filename";
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename='.$filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
Please Use Like as follows,I am using this for me.
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=".$fileName);
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
In place of application/vnd.ms-excel use your file format.It is for Microsoft Excel.
Try with this:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=test.csv');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
You can see more about download files with PHP here:
http://php.net/manual/en/function.readfile.php
Try With Below code , it's work for me
$file =$_SESSION['csvf'];
$filename = $file."_".date("Y-m-d_H-i",time()).".csv";
header ( "Content-type: text/csv" );
header("Content-Disposition: attachment; filename=".$filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
print($file);
exit ();
Below is a snippet for a .zip file with some descriptions on some information that header requires, perhaps a good practice is to get the information and some validations before writing headers.
Another shorter example is also included,
// defines filename, type, path, size and a reference to file (handler)
// to set as values for file header
$filename = $survey_id . '.zip';
// define path to the file to be get file size on the next line
$filepath = [path to file]. '/' . $filename;
// used by 'Content-length'
$filesize = filesize($filepath);
// using fopen to get a file handler, 'r' for read, 'b' for binary (zip file)
$file_pointer = fopen($filepath, 'rb');
// check if file exists
if(is_file($filepath))
{
// valid file?
if($filesize && $file_pointer)
{
// some required header information to describe file, see [docs][1]
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: zip file");
header("Content-Type: application/zip");
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Transfer-Encoding: binary");
header("Content-length: " . $filesize);
fpassthru($file_pointer);
// close
fclose($file_pointer);
}
}
Also, checkout readfile(), a shorter snippet below
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
Hope this helps!
Just escape your php properly like so:
header('Content-Disposition: attachment; filename=' . time() . '.export.csv');
This example will put a UNIX timestamp prepended to the file name. Of course you could get crazy with programmatically using variables or inbuilt php functions, but this is just the example.
Here is more of an example. This file name will be produced when running this php code.
2019-05-18-contacts-main-export-by-Garrick.csv
header('Content-Disposition: attachment; filename=' . date("Y-m-d") . '-contacts-main-export-by-' . $uidName . '.csv');
I've written a function to download a file in csv format in php which goes as follows:-
function report_download_csv($fields, $data, $filename) {
global $CFG;
require_once($CFG->dirroot.'/user/profile/lib.php');
$filename = clean_filename($filename.'-'.date('Y-m-d').'.csv');
header("Content-Type: application/download\n");
header("Content-Disposition: attachment; filename=$filename");
header("Expires: 0");
header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
header("Pragma: public");
$row = array();
$date_field = array('registrationdate', 'expirydate', 'startdate', 'enddate');
$totalrow = count($fields);
$row[] = implode(',',$fields)."\n";
foreach($data as $d){
for($i=0;$i<$totalrow;$i++){
$row_d[] = $d->$fields[$i];
}
$row[] = implode(',',$row_d);
$row_d = array();
}
echo implode($row, "\n");
die;
}
However, when I call the function, it simply prints the result in the browser. Is there something I should change in the function?
Try like this..
header('Content-Type: application/csv');
header('Pragma: no-cache');
The following headers should force a download
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"".$filename."\";" );
header("Content-Transfer-Encoding: binary");