简体   繁体   English

php curl从url获取文件内容,强制下载文件,返回错误“来自服务器的空回复”

[英]php curl get file content from url which forces to download file returns error “Empty reply from server”

I am trying to load file content from URL which forces to download file with header Content-Type : application/octet-stream 我正在尝试从URL加载文件内容,这会强制下载标题为Content-Type的文件:application / octet-stream

The code which return error "Empty reply from server": 返回错误“来自服务器的空答复”的代码:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://urltofile.com/file.csv');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

if(!$file = curl_exec($ch)) {

    echo curl_error($ch);

}

curl_close($ch);

echo $file;

I find the solution after few hours! 几个小时后我找到解决方案!

Sending custom headers and user agent with CURL solve this! 发送带有CURL的自定义标头和用户代理可解决此问题!

$ch = curl_init();

$agent="Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3";
$header=[];
$header[]="Accept: text/xml,text/csv,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; 
$header[]="Connection: keep-alive"; 
$header[]="Keep-Alive: 300"; 

curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
curl_setopt($ch, CURLOPT_URL, 'http://urltofile.com/file.csv');
curl_setopt($ch, CURLOPT_USERAGENT, $agent); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

if(!$file = curl_exec($ch)) {

    echo curl_error($ch);

}

curl_close($ch);

echo $file;

I hope that this will help someone! 我希望这会对某人有所帮助! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM