用php下载excel文件

时间:2017-07-13 12:54:56

标签: php excel download

我需要从外部链接下载excel文件。

我写了2个代码,但都出错了:

第一个:

$url = "www.example.com";
$data = file_get_contents($url);
$destination = "test.xlsx";
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file); 

运行此脚本后,我无法使用test.xlsx文件, 得到并出类拔萃:

Excel cannot open this file, The file format or file extension is not valid. 
Verify that the file has not been corrupted and that the file extension matches the format of the file.
第二个:

$ch = curl_init();
$targetFile = fopen( 'test.xlsx', 'w' );
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:             
application/vnd.ms-excel"));
curl_setopt($ch, CURLOPT_URL,     
www.example.com');
curl_setopt( $ch, CURLOPT_FILE, $targetFile );
curl_exec( $ch );
fclose( $targetFile );

我又得到了同样的错误。当我试图从浏览器打开该链接时,xlsx文件会自动下载,但我无法从代码下载该链接,请帮助

1 个答案:

答案 0 :(得分:0)

我对这个问题的理解就像是

yoursite www.yoursite.com

带文件的网站 www.sitewithfile.com/path/file.xlxs

你使用链接的东西

<a href='www.sitewithfile.com/path/file.xlxs' target='__blank'>Download</a>