2013-02-28 35 views
0

大文件我使用下面的代碼使用PHP下載使用PHP

//some php page parsing code 
$url = 'http://www.domain.com/'.$fn; 
$path = 'myfolder/'.$fn; 
$fp = fopen($path, 'w'); 
$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_FILE, $fp); 
$data = curl_exec($ch); 
curl_close($ch); 
fclose($fp); 
// some more code 

下載一些遠程服務器上的文件,但不是在目錄中下載和保存文件時,它顯示該文件的內容(垃圾字符文件是zip)直接在瀏覽器上。

我想這可能與頭內容的問題,但不完全知道...

感謝

+0

那麼,這裏有什麼問題? – 2013-02-28 07:06:38

+1

您的代碼正在爲我工​​作。 – diolemo 2013-02-28 07:20:24

回答

1

我相信你需要:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 

使curl_exec()返回數據和:

$data = curl_exec($ch); 
fwrite($fp, $data); 

獲取實際寫入的文件。

1

http://php.net/manual/en/function.curl-setopt.php提到:

CURLOPT_RETURNTRANSFER:TRUE返回傳送作爲curl_exec的返回值的字符串(),而不是直接將其輸出出來。

所以您可以在curl_exec行之前只需添加這行:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 

,你將不得不在$數據變量的內容。

+0

感謝大家,我使用您的反饋意見,對捲曲選項有了更好的理解,謝謝 – Nitin 2013-02-28 09:02:07

1

使用包含錯誤處理的以下函數。

// Download and save a file with curl 
function curl_dl_file($url, $dest, $opts = array()) 
{ 
    // Open the local file to save. Suppress warning 
    // upon failure. 
    $fp = @fopen($dest, 'w+'); 

    if (!$fp) 
    { 
     $err_arr = error_get_last(); 
     $error = $err_arr['message']; 
     return $error; 
    } 

    // Set up curl for the download 
    $ch = curl_init($url); 

    if (!$ch) 
    { 
     $error = curl_error($ch); 
     fclose($fp); 
     return $error; 
    } 

    $opts[CURLOPT_FILE] = $fp; 

    // Set up curl options 
    $failed = !curl_setopt_array($ch, $opts); 

    if ($failed) 
    { 
     $error = curl_error($ch); 
     curl_close($ch); 
     fclose($fp); 
     return $error; 
    } 

    // Download the file 
    $failed = !curl_exec($ch); 

    if ($failed) 
    { 
     $error = curl_error($ch); 
     curl_close($ch); 
     fclose($fp); 
     return $error; 
    } 

    // Close the curl handle. 
    curl_close($ch); 

    // Flush buffered data to the file 
    $failed = !fflush($fp); 

    if ($failed) 
    { 
     $err_arr = error_get_last(); 
     $error = $err_arr['message']; 
     fclose($fp); 
     return $error; 
    } 

    // The file has been written successfully at this point. 
    // Close the file pointer 
    $failed = !fclose($fp); 

    if (!$fp) 
    { 
     $err_arr = error_get_last(); 
     $error = $err_arr['message']; 
     return $error; 
    } 
}