php - 使用 PHP 从间接链接下载 XLSX 文件
问题描述
我希望能够使用 PHP 将以下文件下载到我的服务器:
https://www.arcgis.com/sharing/rest/content/items/b5e7488e117749c19881cce45db13f7e/data
问题是它不是文件的直接链接,为了解决这个问题,我尝试使用 curl 但我没有成功。有什么建议么?我尝试使用以下 curl 片段:
但是,输出是一个空的 XLSX 文件。
解决方案
引用的示例处理常规的非 ssl 端点,并省略了CURLOPT_FOLLOWLOCATION
允许 curl 跟随重定向的选项。以下应该可以正常下载文件 - 您需要下载cacert.pem
并编辑显示的 curl 函数的副本。
<?php
$url='https://www.arcgis.com/sharing/rest/content/items/b5e7488e117749c19881cce45db13f7e/data';
$target=__DIR__ . '/covid-19.xlsx';
$hndl=fopen( $target, 'w' );
$options=array(
CURLOPT_FILE => $hndl
);
$res=curl( $url, $options );
if( $res->info->http_code==200 && file_exists( $target ) )echo 'ok';
fclose( $hndl );
function curl( $url=NULL, $options=NULL ){
/*
Edit this to suit your environment.
Download a copy from https://curl.haxx.se/docs/caextract.html
*/
$cacert='c:/wwwroot/cacert.pem';
$curl=curl_init();
if( parse_url( $url,PHP_URL_SCHEME )=='https' ){
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $curl, CURLOPT_CAINFO, $cacert );
}
curl_setopt( $curl, CURLOPT_URL,trim( $url ) );
curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $curl, CURLOPT_FAILONERROR, true );
curl_setopt( $curl, CURLOPT_HEADER, false );
curl_setopt( $curl, CURLINFO_HEADER_OUT, false );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_BINARYTRANSFER, true );
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 20 );
curl_setopt( $curl, CURLOPT_TIMEOUT, 60 );
curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla the Gorilla' );
curl_setopt( $curl, CURLOPT_MAXREDIRS, 10 );
curl_setopt( $curl, CURLOPT_ENCODING, '' );
if( isset( $options ) && is_array( $options ) ){
foreach( $options as $param => $value ) curl_setopt( $curl, $param, $value );
}
$res=(object)array(
'response' => curl_exec( $curl ),
'info' => (object)curl_getinfo( $curl ),
'errors' => curl_error( $curl )
);
curl_close( $curl );
return $res;
}
?>
推荐阅读
- c# - 我可以从父对象访问子对象变量吗?
- java - 为我的菜单设置背景图像并调整大小
- angular - Angular 按钮中的 Ag Grid 过滤器中的清除和应用不可见
- javascript - 使用 Firebase 部署 SPA 和函数
- splunk - 使用 mstats 过滤掉值
- twig - 如何在树枝中获得时间?
- flutter - Flutter 插件 just_audio 示例错误然后处理
- python - Python:下载 Outlook 附件并在保存时更改文件名
- c# - C# 使用 C++ dll 中的函数,以 std::vector 作为参数
- text - 如何使用 FreeType / HarfBuzz 查找垂直文本的列宽