【问题标题】:How to read xls file return by Content-Disposition: attachment with PHP如何读取 Content-Disposition 返回的 xls 文件:PHP 附件
【发布时间】:2017-08-08 14:05:21
【问题描述】:

当我访问一个链接时,例如:https://demo.com/report?transType=xls 它会返回一个 xls 给我下载。它的响应头:

HTTP/1.1 200 OK
Date: Thu, 16 Mar 2017 19:18:37 GMT
Server: IIS/4.0 (Windows XP)
Content-Disposition: attachment; filename*="utf-8''demo.xls
Vary: Accept-Encoding,User-Agent
Content-Length: 14848
Keep-Alive: timeout=10, max=1000
Connection: Keep-Alive

内容类型:文本/html

如何使用 PHP(CURL、Socket...)将此文件下载到我的服务器?我尝试了 CURL,但它不起作用。保存的文件无法读取:(这是我的代码:

$op = curl_init();
curl_setopt ($op, CURLOPT_URL, 'https://demo.com/report?transType=xls');
curl_setopt ($op, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($op, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($op, CURLOPT_TIMEOUT, 60);
curl_setopt ($op, CURLOPT_POST, 1); 
curl_setopt ($op, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($op, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($op, CURLOPT_BINARYTRANSFER, 1);

$response = curl_exec($op); 
@file_put_contents('saved.xls', $response);

请帮帮我:(

【问题讨论】:

    标签: php curl content-disposition


    【解决方案1】:

    要在 php 中使用 curl 下载文件,您必须使用如下代码:

    <?php
    //File to save the contents to
    $fp = fopen ('theFile.xls', 'w+'); 
    $url = "https://demo.com/report?transType=xls";
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    //give curl the file pointer so that it can write to it
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $data = curl_exec($ch);//get curl response
    //done
    curl_close($ch);
    fclose($fp);
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      相关资源
      最近更新 更多