《PHP學(xué)習(xí):從性能方面考慮PHP下載遠(yuǎn)程文件的3種方法》要點:
本文介紹了PHP學(xué)習(xí):從性能方面考慮PHP下載遠(yuǎn)程文件的3種方法,希望對您有用。如果有疑問,可以聯(lián)系我們。
PHP實例今天在做導(dǎo)出Excel的時候,總是要測試導(dǎo)出的Excel文件,頻繁的下載和打開,很麻煩就想著寫段代碼一氣呵成? 服務(wù)端導(dǎo)出Excel==>下載Excel文件到本地==>并打開的操作.
PHP實例這里摘出PHP下載遠(yuǎn)端文件的方案,以備忘.其中第3種辦法考慮到文件過大時的性能問題.
PHP實例3種方案:
PHP實例-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
PHP實例方案1,適用于小文件
PHP實例直接使用fopen()/file_get_contents()獲取文件流并用file_put_contents()寫入
PHP實例
<?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);
?>
PHP實例方案2:通過Curl獲取內(nèi)容
PHP實例
<?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);
?>
PHP實例第1,2種方案存在一個問題,就是在寫入本地磁盤之前,文件會被讀入內(nèi)存中,那么當(dāng)文件很大的時候,可能會超出內(nèi)存而崩潰
PHP實例即使你的內(nèi)存設(shè)置的足夠的大,那這也是不別要的開銷
PHP實例解決辦法是:直接給CURL一個可寫的文件流來讓它自己來解決這個問題(通過 CURLOPT_FILE選項),這樣就要先創(chuàng)建一個文件指針給它.
PHP實例
<?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);
?>
PHP實例?以上內(nèi)容給大家介紹了從性能方面考慮PHP下載遠(yuǎn)程文件的3種辦法,希望大家喜歡.
《PHP學(xué)習(xí):從性能方面考慮PHP下載遠(yuǎn)程文件的3種方法》是否對您有啟發(fā),歡迎查看更多與《PHP學(xué)習(xí):從性能方面考慮PHP下載遠(yuǎn)程文件的3種方法》相關(guān)教程,學(xué)精學(xué)透。維易PHP學(xué)院為您提供精彩教程。
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/7967.html