2013-07-08 71 views
0

我遇到了強制下載文件的問題。PHP強制下載轉到網頁

我使用PHPExcel根據從我們的數據庫中提取的信息創建xls文件。這一切工作正常,Excel文件按要求工作。

然後,我嘗試使用以下功能強制下載創建的文件。但它下載網頁而不是文件。

目前在Win XP SP3,Notepad ++,XAMPP(Apache 2.4.3,PHP 5.4.7)上開發。

**功能如下

public function downloadfile($file){ 
    if(file_exists($file) && is_file($file)){   
     //ob_start(); 
     echo $file; 
     echo "in file exists"; 
     header('Content-Description: File Transfer'); 
     header('Content-Type: application/octet-stream'); 
     header('Content-Disposition: attachment; filename='.basename($file)); 
     header('Content-Transfer-Encoding: binary'); 
     header('Expires: 0'); 
     header('Cache-Control: must-revalidate'); 
     header('Pragma: public'); 
     header('Content-Length: ' . filesize($file)); 
     ob_clean(); 
     flush(); 
     readfile($file);  
     //ob_end_flush(); 
    }else 
     echo "file or location does not exist <br>";  
     echo $file; 
} 

任何幫助,將不勝感激。 在此先感謝

回答

2

如果它的Excel文件,然後只是重定向到該網址,並且默認它會要求文件下載。

header("Location: http://site.com/path/to/file/filename.xlsx"); 
/* Make sure that code below does not get executed when we redirect. */ 
exit; 

如果在JavaScript給

location.href = 'http://site.com/path/to/file/filename.xlsx'; 
1
header("Content-Type: application/vnd.ms-excel; charset=UTF-8"); 
header("Content-Disposition: inline; filename=\"" . $fileName . ".xls\""); 
header("Pragma: no-cache"); 
header("Expires: 0"); 
readfile($filePath); 

試試這個