首页 > 解决方案 > 在 php 中下载一个通过 url 触发的 csv 文件

问题描述

我尝试下载通过 URL 触发的 csv 文件。我执行 get 请求,然后返回结果,但内容只是 HTML 代码。我没有取回 csv 文件。如果我print_r是获取请求的结果,则 csv 文件开始在浏览器中下载,但我需要在 PHP 中下载 csv 文件。

有没有办法从 PHP 中下载 csv 文件?任何帮助将不胜感激。以下是我到目前为止的代码。

获取请求...

require_once('hhb_.inc.php');
    $hc = new hhb_curl('', true);

            $output_filename = "hotProduct_Laptop_Parts.csv";
                $fp = fopen($output_filename, 'w+');
                set_time_limit(0); // unlimited max execution time
                $contents=$hc->setopt_array(array(
                  CURLOPT_FILE    => $fp,
                  CURLOPT_RETURNTRANSFER => 1,
                  CURLOPT_FOLLOWLOCATION=> true,
                  CURLOPT_TIMEOUT =>  28800, // set this to 8 hours so we dont timeout on big files
                  CURLOPT_URL     => 'https://portals.aliexpress.com/adcenter/hot_product_download.do?categoryId=200001083&categoryName=Laptop%20Parts%20&%20Accessories',
                  CURLOPT_HTTPHEADER => array(
                      'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                      'Referer: https://portals.aliexpress.com/adcenter/hotProductRecommend.htm?categoryId=7',
                      'accept-language: en-US,en;q=0.5',
                      'accept-encoding: gzip, deflate, br',
                      'upgrade-insecure-requests:   1',
                      'te:  trailers',
                      'authority:   portals.aliexpress.com'
                       ,

                  )
                )
                )->exec()->getStdOut();

        print_r($contents);


            // the following lines write the contents to a file in the same directory (provided permissions etc)

            fwrite($fp, $contents);
            fclose($fp);

标签: phpcurl

解决方案


您需要先登录并拥有有效的登录 cookie,然后才能下载该文件。如果您尝试在未登录的浏览器中查看该 URL,您首先会看到登录页面!该页面基本上是在说“先登录”。

您尚未发布重现问题所需的代码,因为您尚未发布重现问题所需的 URL。我已投票关闭该问题,因为我无法复制它。

您的问题几乎可以肯定是您需要在下载文件之前获取 cookie(这很常见),但由于您没有共享您尝试下载的 url,我无法检查该理论。在您分享相关网址之前,我们无能为力。


推荐阅读