• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP下载远程文件的3种方法以及性能考虑

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

今天在做导出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/


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP中抽象类和接口的区别发布时间:2022-07-10
下一篇:
php里Array2xml发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap