将xls文件保存到目录并在php中下载
我有一个php代码,它从postgres数据库中选择一个查询,创建一个xls文件并下载。代码如下:将xls文件保存到目录并在php中下载,php,excel,postgresql,zipfile,Php,Excel,Postgresql,Zipfile,我有一个php代码,它从postgres数据库中选择一个查询,创建一个xls文件并下载。代码如下: <?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"';
<?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";
}
}
?>
问题在于变量。当文件名有空格时,必须使用如下引号:
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename='$xls_filename'");
您可以使用下面的代码,工作良好
$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;
}
您可以使用output\u buffering
来执行此操作。看一看下面的例子。你的文件名是什么?如果合适,请记住接受答案@Esteann Afonso