0

我知道以前有人问过这个类似的问题,但我找不到针对我的具体问题的解决方案。我有这段代码,它保存到一个文件中,并在从浏览器运行时立即下载到桌面。但我需要将其保存在服务器上。如何使用此特定代码执行此操作?

我需要$files先将文件保存到变量中吗?

<?php


header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download"); 
header("Content-Disposition: attachment;filename=export_".date('n-j-Y').".xls "); 
header("Content-Transfer-Encoding: binary ");

exit();

?>  
4

1 回答 1

3

Here's some normal code:

<?php
echo "hey F4LLCON!";
?>

Executed, it behaves like we expect:

% php output.php 
hey F4LLCON!

Now I'll modify it to add output buffering and save to the file and write to stdout (using regular echo calls!):

<?php
ob_start();
echo "hey F4LLCON!";
$output_so_far = ob_get_contents();
ob_clean();
file_put_contents("/tmp/catched.txt", $output_so_far);
echo $output_so_far;
?>

After executing, the output in the file catched.txt is equal to what we got earlier (and still get) on stdout:

hey F4LLCON!

Now I'll modify it again to show how generators from PHP 5.5 will provide you with an elegant solution that doesn't need to sacrifice performance (the previous solution requires you to save all the intermediate content in one giant output buffer):

<?php
$main = function() {
    yield "hey F4LLCON!";
};
$f = fopen("/tmp/catched2.txt", "wb");
foreach ($main() as $chunk) { fwrite($f, $chunk); echo $chunk; }
fclose($f);
?>

We aren't storing everything in one giant buffer, and we can still output to file and stdout simultaneously.

If you don't understand generators, here's a solution where we pass a callback "print" function to main(), and that function is used every time we want to output (only one time here).

<?php
$main = function($print_func) {
    $print_func("hey F4LLCON!");
};
$f = fopen("/tmp/catched3.txt", "wb");
$main(function($output) use ($f) {
    fwrite($f, $output);
    echo $output;
});
fclose($f);
?>
于 2013-06-20T11:19:43.030 回答