2016-04-14 91 views
0

我使用函數通過私有API下載文件。 一切都很好,下載中/小文件,但大文件是不可能的,因爲它使用太多的內存。CURL_RETURNTRANSFER下載大文件

這裏是我的功能:

protected function executeFile($method, $url, $params=array(), $as_user=null) { 

    $data_string = json_encode($params); 
    $method = strtoupper($method); 

    $ch = curl_init(); 

    if($method == 'GET') { 
     $url = $this->options['api_url'].$url.'?'; 
     $url .= $this->format_query($params); 
     curl_setopt($ch, CURLOPT_URL, $url); 
    } else { 
     curl_setopt($ch, CURLOPT_URL, $this->options['api_url'].$url); 
    } 

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

    if($as_user) { 
     curl_setopt($ch, CURLOPT_HTTPHEADER, array(
     'Content-Type: application/json', 
     'Content-Length: ' . strlen($data_string), 
     'Token: '.$this->token, 
     'As: '.$as_user 
     )); 
    } else { 
     curl_setopt($ch, CURLOPT_HTTPHEADER, array(
     'Content-Type: application/json', 
     'Content-Length: ' . strlen($data_string), 
     'Token: '.$this->token 
     )); 
    } 

    $result_json = curl_exec($ch); 
    $curl_info = curl_getinfo($ch); 


    $return    = array(); 
    $return["result"] = $result_json; 
    $return["entete"] = $curl_info; 
    return $return; 
} 

我怎麼能優化這個文件下載到磁盤,而不是內存?

謝謝

+0

這個問題已經在這裏找到答案:http://stackoverflow.com/questions/6409462/downloading -a-large-file-using-curl –

回答

1

使用CURLOPT_FILE。它會要求保存下載的文件指針。

代碼就會像

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$fp = fopen("your_file", 'w+'); 
curl_setopt($ch, CURLOPT_FILE, $fp); 

curl_exec ($ch); 
0

您可以使用CURLOPT_FILE,像這樣:

protected function executeFile($method, $url, $params=array(), $as_user=null) { 

    $data_string = json_encode($params); 
    $method = strtoupper($method); 
    $fp = fopen ('savefilepath', 'w+'); 

    $ch = curl_init(); 

    if($method == 'GET') { 
     $url = $this->options['api_url'].$url.'?'; 
     $url .= $this->format_query($params); 
     curl_setopt($ch, CURLOPT_URL, $url); 
    } else { 
     curl_setopt($ch, CURLOPT_URL, $this->options['api_url'].$url); 
    } 

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_FILE, $fp); 

    .... 

    curl_exec($ch); 
    fclose($fp); 
    ..... 
    return $return; 
} 
+0

我試過這個,但是Firefox告訴我「源文件無法讀取」...... 但是文件被正確地保存到服務器上的磁盤! – TheMadCat

+0

只需一個快速的snip代碼,可能需要在寫入磁盤後關閉文件:'fclose($ fp);'。檢查更新的附加代碼的位置。 –

+0

我試過了,還包括一個curl_close($ ch);但同樣的錯誤,我不明白爲什麼......感謝您的幫助! – TheMadCat