I have a php code that selects an query from a postgres db and creates a xls file and downloads the same. The code is as follows :
<?php
$xls_filename = 'filename.xls'; // Define Excel (.xls) file name
$Connect = pg_connect ("host=xxxx port=5432 dbname=xxxx user=xxx password=xxx");
$sql = 'SELECT * FROM "tablename"';
$result = pg_query($sql);
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$xls_filename");
header("Pragma: no-cache");
header("Expires: 0");
// Define separator (defines columns in excel & tabs in word)
$sep = "\t"; // tabbed character
// Start of printing column names as names of fields
for ($i = 0; $i<pg_num_fields($result); $i++) {
echo pg_field_name($result,$i) . "\t";
}
print("\n");
// End of printing column names
// Start while loop to get data
while($row = pg_fetch_row($result))
{
$schema_insert = "";
for($j=0; $j<pg_num_fields($result); $j++)
{
if(!isset($row[$j])) {
$schema_insert .= "".$sep;
}
elseif ($row[$j] != "") {
$schema_insert .= "$row[$j]".$sep;
}
else {
$schema_insert .= "".$sep;
}
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
}
?>
I want to zip this xls file which is created rather then just downloading it. How do I create a xls file in the directory instead of downloading it.
The problem is your variable.when your file name has space you have to use quotes like below:
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename='$xls_filename'");
You can use below code that work fine
$fileNames = WWW_ROOT . 'uploads' . DS . 'export' . DS . 'DYNAMIC_FILE_NAME_'. $ANY_DYNAMIC_PART.'.xls';//Dynamic Path of the directory
if (file_exists($fileNames)) {
$file = $fileNames;
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=\"NEWFILENAME.xls\"");
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
readfile($fileNames);exit;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.