I am trying to export some data to CSV using PHP.
My code:
function download_send_headers($filename) {
// disable caching
$now = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// disposition / encoding on response body
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
}
$givenTerm = $_POST['TextBoxList'];
$sql_query = "select * from some_table where key=".$givenTerm;
$result = sqlsrv_query($conn,$sql_query);
$r1 = array();
$file = fopen("php://output", 'w');
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_NUMERIC)){
$valuesArray=array();
foreach($row as $name => $value)
{
$valuesArray[]=$value;
}
fputcsv($file,$valuesArray);
}
fclose($file);
download_send_headers("data_export_" . date("Y-m-d") . ".csv");
die();
Here I am receiving a search-value from a form in another page and then triggering a query based on it. The code is working fine for smaller data-sets(up to 100). But when the number of rows is more in the result (around 600-700) then the code crashes. Please tell me how to fix this.
P.S. I am using Sql Server 2012 for the database.
Instead of first getting all results in a single array and then outputting it, you could also fetch it row by row and outputting each row directly.
That way you won't need the massive amount of memory to fit the entire array in.
Related
I'm trying to fetch and download data using php to csv file, for task i found a good answer, this is working for me on all browser except firefox.
$s = $master->getUser();
function array2csv(array &$array)
{
if (count($array) == 0) {
return null;
}
ob_start();
$df = fopen("php://output", 'w');
fputcsv($df, array_keys(reset($array)));
foreach ($array as $row) {
fputcsv($df, $row);
}
fclose($df);
return ob_get_clean();
}
function download_send_headers($filename) {
/*header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename={$filename}");
// Disable caching
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
header("Pragma: no-cache"); // HTTP 1.0
header("Expires: 0"); // Proxies*/
// disable caching
$now = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// disposition / encoding on response body
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
}
download_send_headers(site_title .' '. date("d M Y") . ".csv");
echo array2csv($s);
die();
In Firefox file extension does not showing in csv, it is looking like application file.
Have you tried removing these in your code:
header("Content-Type: application/force-download");
header("Content-Type: application/download");
Just retain:
header("Content-Type: application/octet-stream");
fputcsv function write data fro 6th row. But I want to write data from first row.
what I have tried
// disable caching
$now = gmdate("D, d M Y H:i:s");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// disposition / encoding on response body
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
$df = fopen("php://output", 'w');
fputcsv($df, array_keys(reset($array)));
foreach ($array as $row) {
fputcsv($df, $row);
}
fclose($df);
what looks like in MS-Excel
what looks like in Notepad
I have a simple web page which pulls some data from DB and displays it in a html table and stores the data in some session variables.
I have a button "Export to csv" which calls a page which exports the results to a csv file.
The code for ExportToCsv file is:
<?php
session_start();
include "conn/sqlserverConn.php";
function download_send_headers($filename) {
// disable caching
$now = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// disposition / encoding on response body
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
}
$data = $_SESSION['data'];
$rows = $_SESSION['row'];
$header = $_SESSION['header'];
download_send_headers("data_export_" . date("Y-m-d") . ".csv");
$file = fopen("php://output", 'w');
fputcsv($file,$header);
for($i=0; $i<$rows; ++$i)
{
$valuesArray=array();
foreach($data[$i] as $name => $value)
{
$valuesArray[]=$value;
}
fputcsv($file,$valuesArray);
}
fclose($file);
die();
?>
My code is working flawlessly in firefox but it is not working in chrome or IE. On chrome and IE it is showing error 404 (Object not found!). Please tell me what is the problem ?
As outlined in the blog article at: http://www.exchangecore.com/blog/php-output-array-csv-headers/, I tested the following and it worked in IE8-11, and in chrome version 34. I presume it will work in other browsers fine as well.
Headers to use:
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: text/csv');
header('Content-Disposition: attachment;filename=' . $fileName);
i want to create a link to download an excel file from the root in server computer, using php. so i wrote a simple code as below,
<?php
header("Content-disposition: attachment; filename=example.xls");
header("Content-type: application/vnd.ms-excel");
readfile("example.xls");
?>
it then can be downloaded however when i want to open it, i got the error saying the file i downloaded is in a different format than specified by the file extension. i also tried the same method with jpeg file and didnt get the same error but when i click it, it shows nothing. can someone help me? im not very good with programming. thank you in advance!
Try this
$file='example.xls'; $filesize=filesize($file);
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: inline; filename="'.basename($file).'"');
header("Content-Length: " . $filesize);
$fh = fopen("$file, "rb");
// output file
while(!feof($fh))
{
# output file without bandwidth limiting
print(fread($fh, filesize($file)));
}
fclose($fh);
My code kinda weird, i don't know what would be the problem of my code.. here's my code.
$project_name = $_POST['project_name'];//example the retrieved data is Testing Project
$quote_id = $_POST['quote_id'];//example the retrieved data is 34425
$date = date("M/d/y");
$as_agent = $_POST['as_agent'];//example the retrieved data is John Doe
$name_for_project = $project_name.' '.$quote_id.' '.$date.' '.$as_agent;
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename='".$name_for_project.".xls'");
ob_start();
//The rest of the code is Workbook
echo"
<?xml version='1.0'?>
<?mso-application progid='Excel.Sheet'?>
<Workbook
xmlns='urn:schemas-microsoft-com:office:spreadsheet'
xmlns:o='urn:schemas-microsoft-com:office:office'
xmlns:x='urn:schemas-microsoft-com:office:excel'
xmlns:ss='urn:schemas-microsoft-com:office:spreadsheet'
xmlns:html='http://www.w3.org/TR/REC-html40'>
<DocumentProperties xmlns='urn:schemas-microsoft-com:office:office'>
<Version>11.8036</Version>
</DocumentProperties>
<ExcelWorkbook xmlns='urn:schemas-microsoft-com:office:excel'>
<WindowHeight>6795</WindowHeight>
<WindowWidth>8460</WindowWidth>
<WindowTopX>120</WindowTopX>
<WindowTopY>15</WindowTopY>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>";
//so on and so fort...
When this code runs it only capture the $project_name value.. Please Help me... Thank you..
The following line header("... will prompt to save a file with apostrophes to the beginning and end of the file.
Example: 'project_quote_id_2013-08-31_as_agent.xls'
header("content-disposition: attachment;filename='".$name_for_project.".xls'");
which should be changed to:
header("content-disposition: attachment;filename=".$name_for_project.".xls");
The code below will produce/echo a saveable file called: project_quote_id_2013-08-31_as_agent.xls (as of today's date for testing).
If, and as Aiden stated in his answer, you are using slashes as your seperator for your $date variable, you will encounter problems.
Try to avoid using spaces for seperators, use hyphens and/or underscores to seperate your values.
For example, this will save to prompt to a file with some dummy content.
<?php
$date = gmdate('Y-m-d', time() - 3600 * $hours);
$project_name = "project";
$quote_id = "quote_id";
$as_agent = "as_agent";
$name_for_project = $project_name.'_'.$quote_id.'_'.$date.'_'.$as_agent;
$file = $name_for_project.".xls";
// start buffering
ob_start();
// sample dynamically generated data
echo '<table border="1"> ';
echo '<tr><th>Name</th><th>Age</th></tr>';
for ($i=0; $i<=5; $i++) { echo "<tr><td>Name$i</td><td>".($i+1)."</td></tr>";
}
echo '</table>';
$content = ob_get_contents();
ob_end_clean();
header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Content-type: application/vnd.ms-excel;charset:UTF-8");
header('Content-length: '.strlen($content));
header('Content-disposition: attachment; filename='.basename($file));
// output all contents
echo $content;
exit;
?>
will produce a file called: project_quote_id_2013-08-31_as_agent.xls (as of today's testing date) and will prompt the user to save it under that name.
The rest of the code that is to insert the actual content, will need to be inserted accordingly, because there was nothing else posted in regards to variables or text associated with the question/code.
Do any of your other variables contain invalid characters for a file name? E.g. If you declared your $date as 30/08/2013 then php will not concatenate your variables past the invalid character.
Spaces affect in naming filename. what i do is transform my code into.
$project_name = $_POST['project_name'];//example the retrieved data is Testing Project
$quote_id = $_POST['quote_id'];//example the retrieved data is 34425
$date = date("M/d/y");
$as_agent = $_POST['as_agent'];//example the retrieved data is John Doe
$proj_name = str_replace(' ', '', $project_name);
$as_agent = str_replace(' ', '', $as_agent);
$name_for_project = $proj_name."-".$quote_id."-".$date."-".$as_agent;
header("Content-Type: application/vnd.ms-excel");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=$name_for_project.xls");
Thanks to #Fred -ii-