国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > PHP > 正文

PHP下載遠(yuǎn)程文件的3種方法以及性能考慮

2020-03-22 19:45:25
字體:
供稿:網(wǎng)友
  • 今天在做導(dǎo)出Excel的時候,總是要測試導(dǎo)出的Excel文件,頻繁的下載和打開,很麻煩

    就想著寫段代碼一氣呵成 服務(wù)端導(dǎo)出Excel==>下載Excel文件到本地==>并打開的操作。

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

    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('librehtml' target='_blank'>office ./test.xls', $out, $status);?>

      

    方案2:通過Curl獲取內(nèi)容

    <?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種方案存在一個問題,就是在寫入本地磁盤之前,文件會被讀入內(nèi)存中,那么當(dāng)文件很大的時候,可能會超出內(nèi)存而崩潰

    即使你的內(nèi)存設(shè)置的足夠的大,那這也是不別要的開銷

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

    <?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://www.cnblogs.com/phpgcs/

    PHP編程

    鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。

  • 發(fā)表評論 共有條評論
    用戶名: 密碼:
    驗證碼: 匿名發(fā)表
    主站蜘蛛池模板: 深州市| 大丰市| 富平县| 文成县| 吴川市| 平南县| 梅河口市| 沧源| 镇安县| 永昌县| 蒙阴县| 北宁市| 安乡县| 镇远县| 长寿区| 翼城县| 大方县| 神农架林区| 威远县| 阿尔山市| 叶城县| 融水| 雅安市| 余庆县| 万年县| 齐河县| 大名县| 阿克苏市| 新巴尔虎左旗| 武平县| 方山县| 沙雅县| 余干县| 安塞县| 山东省| 彩票| 射洪县| 博野县| 通州区| 夹江县| 泸水县|