php - 在 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);
解决方案
您需要先登录并拥有有效的登录 cookie,然后才能下载该文件。如果您尝试在未登录的浏览器中查看该 URL,您首先会看到登录页面!该页面基本上是在说“先登录”。
您尚未发布重现问题所需的代码,因为您尚未发布重现问题所需的 URL。我已投票关闭该问题,因为我无法复制它。
您的问题几乎可以肯定是您需要在下载文件之前获取 cookie(这很常见),但由于您没有共享您尝试下载的 url,我无法检查该理论。在您分享相关网址之前,我们无能为力。
推荐阅读
- sql-server - can you drop a table in sql server while it is being used in another session in a select statement?
- visual-studio - 每次安装Win10 SDK(任何版本)都会挂起
- ios - 如何获得可访问性以识别一个 UITextView 中的两个超链接
- reactjs - 表达 multer 没有从反应中得到 req.body
- javascript - 我收到此错误:“来自 useState() 和 useReducer() Hooks 的状态更新不支持第二个回调...”当我更改状态时
- qt - 为 Qt Framebuffer 指定像素格式
- javascript - 比较两个数组以检索值
- android - 有什么方法可以在状态栏后面绘制 BottomSheetDialogFragment 吗?
- python - 使用元组的 For 循环
- python - 使用 turbodbc 连接到 MSSQL 时出错