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

首頁 > 網(wǎng)站 > 幫助中心 > 正文

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

2024-07-09 22:40:27
字體:
供稿:網(wǎng)友

今天在做導(dǎo)出Excel的時(shí)候,總是要測試導(dǎo)出的Excel文件,頻繁的下載和打開,很麻煩就想著寫段代碼一氣呵成  服務(wù)端導(dǎo)出Excel==>下載Excel文件到本地==>并打開的操作。

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

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

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

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

<?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);?> 

 以上內(nèi)容給大家介紹了從性能方面考慮PHP下載遠(yuǎn)程文件的3種方法,希望大家喜歡。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 黄骅市| 和田县| 确山县| 开封县| 岚皋县| 洞头县| 寻甸| 蛟河市| 鄂温| 康保县| 珠海市| 陇西县| 山阴县| 德化县| 应城市| 南宁市| 永州市| 湘阴县| 高安市| 怀远县| 和顺县| 延长县| 昌邑市| 涞源县| 宁陕县| 安泽县| 九龙县| 分宜县| 新竹县| 邵武市| 康定县| 西宁市| 盘山县| 上虞市| 清丰县| 建始县| 旌德县| 青龙| 东平县| 邢台市| 南雄市|