【问题标题】:Download excel file with php用php下载excel文件
【发布时间】:2017-12-18 06:33:13
【问题描述】:

我需要从外部链接下载一个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 错误:

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 文件会自动下载,但我无法从代码中下载该链接,请帮助

【问题讨论】:

  • 您是否查看了代码加载文件?可能有一些错误吗?还是网站需要授权?
  • @IvanBolnikh 我可以从浏览器访问该文件,所以授权不是答案,我没有得到你答案的第一部分。
  • @PouryaFard - 它仍然可能是授权....有些网站不允许访问,除非通过浏览器,以防止人们编写脚本来访问他们的数据
  • @Mark Ba​​ker,如果我在 curl opts 中设置用户代理,授权会好吗?
  • 这一切都取决于相关网站的检查方式

标签: php excel download


【解决方案1】:

我对这个问题的理解是这样的

您的网站 www.yoursite.com

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

你使用链接的事情

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

【讨论】:

猜你喜欢
  • 2020-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 2014-09-01
相关资源
最近更新 更多