2012-05-09 18:40
浏览 33

使用php curl下载并保存gzip文件

I am trying to download a gzip file using curl and php and saving it in a specified location. Below is the code that I am using but everytime it's saving an empty file allthough the gzip file that it's downloading is proper

$file_zip = 'abc.gz'
$fp = fopen("$file_zip", "w"); 
$request = curl_init();
$headers = array('Content-type: application/x-gzip','Connection: Close');
curl_setopt($request, CURLOPT_URL, $url);
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($request, CURLOPT_TIMEOUT, 0);
curl_setopt($request, CURLOPT_CONNECTTIMEOUT,0);
curl_setopt($request, CURLOPT_HTTPHEADER,$headers);
curl_setopt($request, CURLOPT_FAILONERROR, true);
curl_setopt($request, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($request, CURLOPT_AUTOREFERER, true);
curl_setopt($request, CURLOPT_BINARYTRANSFER,true);

curl_setopt($request, CURLOPT_FILE, $fp);

$zipFile = curl_exec($request);

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用curl和php下载gzip文件并将其保存在指定位置。 下面是我正在使用的代码,但每次它保存一个空文件,尽管它正在下载的gzip文件是正确的

  $ file_zip ='abc.gz'
 $ fp  = fopen(“$ file_zip”,“w”);  
 $ request = curl_init(); 
 $ headers = array('Content-type:application / x-gzip','Connection:Close'); 
curl_setopt($ request,CURLOPT_URL,$ url); 
curl_setopt(  $ request,CURLOPT_RETURNTRANSFER,1); 
curl_setopt($ request,CURLOPT_TIMEOUT,0); 
curl_setopt($ request,CURLOPT_CONNECTTIMEOUT,0); 
curl_setopt($ request,CURLOPT_HTTPHEADER,$ headers); 
curl_setopt($ request,CURLOPT_FAILONERROR,  true); 
curl_setopt($ request,CURLOPT_FOLLOWLOCATION,true); 
curl_setopt($ request,CURLOPT_AUTOREFERER,true); 
curl_setopt($ request,CURLOPT_BINARYTRANSFER,true); 
 ncurl_setopt($ request,CURLOPT_FILE,$ fp);  
 $ zipFile = curl_exec($ request); 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douwa0280 2012-05-09 19:32

    I found a method that downloads a file to a location with cUrl. Hope it helps:

    function get_file1($file, $local_path, $newfilename) 
        $err_msg = ''; 
        echo "<br>Attempting message download for $file<br>"; 
        $out = fopen($newfilename, 'wb'); 
        if ($out == FALSE){ 
          print "File not opened<br>"; 
        $ch = curl_init(); 
        curl_setopt($ch, CURLOPT_FILE, $out); 
        curl_setopt($ch, CURLOPT_HEADER, 0); 
        curl_setopt($ch, CURLOPT_URL, $file); 
        echo "<br>Error is : ".curl_error ( $ch); 
    }//end function 

    The source is :

    点赞 打赏 评论

相关推荐 更多相似问题