簡體   English   中英

使用 PHP 從間接鏈接下載 XLSX 文件

[英]Download a XLSX file from an indirect link using PHP

我希望能夠使用 PHP 將以下文件下載到我的服務器:

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

問題是它不是文件的直接鏈接,為了解決這個問題,我嘗試使用 curl 但我沒有成功。 有什么建議么? 我嘗試使用以下 curl 片段:

使用 curl 下載間接鏡像文件

但是,output 是一個空的 XLSX 文件。

引用的示例處理常規的非 ssl 端點並省略CURLOPT_FOLLOWLOCATION選項以允許 curl 遵循重定向。 以下應該可以正常下載文件 - 您需要下載cacert.pem的副本並編輯 curl function 所示。

<?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;
    }
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM