Today when doing export Excel, always want to test the exported Excel file, frequent download and open, very troublesome
Just want to write a snippet code one go server export excel==> Download the Excel file to the local ==> and open the operation.
Here is the solution to download the remote file from PHP for forgetting. The 3rd approach takes into account performance issues when the file is too large.
3 options:
-rw-rw-r--1 Liuyuan Liuyuan 470 Feb 18:12 test1_fopen.php
-rw-rw-r--1 Liuyuan Liuyuan 541 Feb 18:06 test2_curl.php
-rw-rw-r--1 Liuyuan Liuyuan 547 Feb 18:12 test3_curl_better.php
Scenario 1, for small files
Get the file stream directly using fopen ()/file_get_contents () and write it with file_put_contents ()
123456789 |
<?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
);
?>
|
Scenario 2: Get content through curl
1234567891011 |
<?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
);
?>
|
1th, there is a problem with 2 scenarios where a file is read into memory before it is written to the local disk, and when the file is large, it may crash beyond memory
Even if your memory settings are large enough, that's not the cost.
The workaround is to give curl a writable file stream to solve this problem by itself (via the curlopt_file option) so that a file pointer is created first.
123456789101112 |
<?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 3 ways to download remote files and performance considerations