首页 > 解决方案 > 使用 PHP 从间接链接下载 XLSX 文件

问题描述

我希望能够使用 PHP 将以下文件下载到我的服务器:

https://www.arcgis.com/sharing/rest/content/items/b5e7488e117749c19881cce45db13f7e/data

问题是它不是文件的直接链接,为了解决这个问题,我尝试使用 curl 但我没有成功。有什么建议么?我尝试使用以下 curl 片段:

使用 curl 下载间接图像文件

但是,输出是一个空的 XLSX 文件。

标签: phpcurl

解决方案


引用的示例处理常规的非 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;
    }
?>

推荐阅读