PHP下載遠程文件的3種方法以及性能考慮


今天在做導出Excel的時候,總是要測試導出的Excel文件,頻繁的下載和打開,很麻煩

就想着寫段代碼一氣呵成  服務端導出Excel==>下載Excel文件到本地==>並打開的操作。

這里摘出PHP下載遠端文件的方案,以備忘。其中第3種方法考慮到文件過大時的性能問題。

原創文章,轉載請注明 http://www.cnblogs.com/phpgcs/

 

3種方案:

-rw-rw-r-- 1 liuyuan liuyuan 470 Feb 20 18:12 test1_fopen.php
-rw-rw-r-- 1 liuyuan liuyuan 541 Feb 20 18:06 test2_curl.php
-rw-rw-r-- 1 liuyuan liuyuan 547 Feb 20 18:12 test3_curl_better.php

 

方案1,適用於小文件

直接使用fopen()/file_get_contents()獲取文件流並用file_put_contents()寫入

<?php
    //an example xls file form baidu wenku
    $url = 'http://bs.baidu.com/wenku4/%2Fe43e6732eba84a316af36c5c67a7c6d6?sign=MBOT:y1jXjmMD4FchJHFHIGN4z:lfZAx1Nrf44aCyD6tJqJ2FhosLY%3D&time=1392893977&response-content-disposition=attachment;%20filename=%22php%BA%AF%CA%FD.xls%22&response-content-type=application%2foctet-stream';

    $fp_input = fopen($url, 'r');
    file_put_contents('./test.xls', $fp_input);

    exec("libreoffice ./test.xls", $out, $status);
?>

  

方案2:通過Curl獲取內容

<?php
    //an example xls file form baidu wenku
    $url = 'http://bs.baidu.com/wenku4/%2Fe43e6732eba84a316af36c5c67a7c6d6?sign=MBOT:y1jXjmMD4FchJHFHIGN4z:lfZAx1Nrf44aCyD6tJqJ2FhosLY%3D&time=1392893977&response-content-disposition=attachment;%20filename=%22php%BA%AF%CA%FD.xls%22&response-content-type=application%2foctet-stream';

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    file_put_contents('./test.xls', curl_exec($ch));
    curl_close($ch);

    exec("libreoffice ./test.xls", $out, $status);
?>

  

第1,2種方案存在一個問題,就是在寫入本地磁盤之前,文件會被讀入內存中,那么當文件很大的時候,可能會超出內存而崩潰

即使你的內存設置的足夠的大,那這也是不別要的開銷

解決方法是:直接給CURL一個可寫的文件流來讓它自己來解決這個問題(通過 CURLOPT_FILE選項),這樣就要先創建一個文件指針給它。

原創文章,轉載請注明 http://www.cnblogs.com/phpgcs/

<?php
    //an example xls file form baidu wenku
    $url = 'http://bs.baidu.com/wenku4/%2Fe43e6732eba84a316af36c5c67a7c6d6?sign=MBOT:y1jXjmMD4FchJHFHIGN4z:lfZAx1Nrf44aCyD6tJqJ2FhosLY%3D&time=1392893977&response-content-disposition=attachment;%20filename=%22php%BA%AF%CA%FD.xls%22&response-content-type=application%2foctet-stream';

    $fp_output = fopen('./test.xls', 'w');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp_output);
    curl_exec($ch);
    curl_close($ch);

    exec("libreoffice ./test.xls", $out, $status);
?>

  

 

參考文章:

http://stackoverflow.com/questions/3938534/download-file-to-server-from-url

http://www.phpriot.com/articles/download-with-curl-and-php

 

擴展閱讀

PHP獲取遠程文件的大小的3種方法

http://wk.yl1001.com/doc_9631373592501870_all.htm

支持斷點續傳功能

http://www.pureweber.com/article/resumable-download/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM