欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2015年12月29日 09:47:07   作者:jerrylsxu  
這篇文章主要介紹了從性能方面考慮PHP下載遠(yuǎn)程文件的3種方法的相關(guān)資料,需要的朋友可以參考下

今天在做導(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("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種方案存在一個問題,就是在寫入本地磁盤之前,文件會被讀入內(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);
?> 

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

相關(guān)文章

最新評論