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


php curl get file content from url which forces to download file returns error "Empty reply from server"

我正在尝试从URL加载文件内容,该URL强制下载具有标头的文件内容类型:application/octet流

返回错误"来自服务器的空回复"的代码:

$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;

几个小时后我找到了解决方案!

使用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;

我希望这能帮助到别人!:)