在 php 中使用 curl 从服务器下载 csv 文件


Download csv file from server using curl in php

我对此感到震惊。我想使用 curl 从网址下载 csv 文件。我已经在堆栈溢出中引用了所有答案并尝试了所有答案。但没有得到我所期望的。我有以下代码。

define("COOKIE_FILE", "cookie.txt");
$path = "settlement_file/test.csv";
set_time_limit(0);
$fp = fopen ($path, 'w+');//This is the file where we save the    information
$ch = curl_init(str_replace(" ","%20",$url));//Here is the file we are downloading, replace spaces with %20
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp); // write curl response to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
curl_exec($ch); // get curl response
curl_close($ch);
fclose($fp);

您必须删除 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 语句。它使curl_exec返回数据而不是将其写入文件。由于它位于curl_setopt($ch, CURLOPT_FILE, $fp);之后,因此只需删除前一行即可。