英文:
Problem with download file via CURL in PHP
问题
我尝试使用curl PHP下载文件时遇到问题。
响应头:
PHP代码:
$filePath = $this->exchangePath . $this->exchangeFile;
$url = $this->exchangeURL;
$fp = fopen($filePath, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
下载后预览文件数据(106Kb):
服务器上的文件数据预览(1.9 Mb - 未来可能会更大,也许达到300Mb或更大):
请帮助我,谢谢。
英文:
I have a problem when i try download file with curl php.
Headers response
PHP Code
$filePath = $this->exchangePath . $this->exchangeFile;
$url = $this->exchangeURL;
$fp = fopen($filePath, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
Preview file data after downloading (106Kb)
Preview file data on server (1.9 Mb - The file will be bigger in the future. Maybe 300Mb or large.)
Help me, please.
答案1
得分: 1
问题在于你忽略了Content-Encoding: gzip
头部。服务器返回的数据是经过gzip编码的,而你没有解压它。
幸运的是,curl内置支持gzip解码(curl基本上一直支持gzip和deflate解码,但现代版本的curl还支持br和zstd)。
要启用支持的编码的自动解码,只需设置:
curl_setopt($ch, CURLOPT_ENCODING, '');
将CURLOPT_ENCODING设置为空字符串会打开所有支持的编码的自动解码。
此外,你应该使用二进制模式wb
来打开文件,以防止Windows干扰你的\n
字节。
英文:
the problem is that you're ignoring that Content-Encoding: gzip
header. The server returns the data gzip-encoded, and you're not un-gzipping it.
Luckily for you, curl has built-in support for gzip decoding (curl has basically supported gzip and deflate decoding forever, but modern versions of curl also support br and zstd)
to enable automatic decoding of supported encodings, simply set
curl_setopt($ch,CURLOPT_ENCODING,'');
- setting CURLOPT_ENCODING to emptystring turns on automatic decoding of all supported encodings.
aalso, you should use the fopen binary mode wb
so Windows doesn't fuck with your \n
bytes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论