[英]How to copy a php file to a csv file and download it?
I want to copy an entire php file into a csv file and download it, but the demo.csv
file that I get is empty. 我想将整个php文件复制到一个csv文件中并下载它,但是我得到的
demo.csv
文件为空。 Why am I getting an empty file? 为什么我得到一个空文件?
The data in the php file is stored per line. php文件中的数据每行存储一次。
<?php
// output headers so that the file is downloaded rather than displayed
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="demo.csv"');
// do not cache the file
header('Pragma: no-cache');
header('Expires: 0');
$handle = fopen("caldataprog.php", "r"); //fileurl
$lines = [];
if (($handle = fopen("caldataprog.php", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
$lines[] = $data;
}
fclose($handle);
}
$fp = fopen('demo.csv', 'w');
foreach ($lines as $line) {
fputcsv($fp, $line);
}
fclose($fp);
?>
What I see is that you finally copy a file to other and don't flush this last. 我看到的是您最终将文件复制到其他文件,并且最后不刷新。
<?php
$source = 'caldataprog.php'; // Presuming it contains raw CSV
$destination = 'demo.csv';
copy($source, $destination);
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="demo.csv"');
readfile($destination); // Send file to user
If caldataprog.php generates CSV and you want to copy the result, you can do : 如果caldataprog.php生成CSV并且您要复制结果,则可以执行以下操作:
$source = 'http://yourwebsite.net/caldataprog.php';
$destination = 'demo.csv';
copy($source, $destination);
You are writing the output data to a file named demo.csv
on your server, and you are downloading a file named demo.csv
in your browser, but they are not the same file . 您正在将输出数据写入服务器上名为
demo.csv
的文件,并且正在浏览器中下载名为demo.csv
的文件,但它们不是同一文件 。
If you want to download the file in your browser, you need to have PHP output the file's contents. 如果要在浏览器中下载文件,则需要PHP输出文件的内容。
You could do this using readfile
, or by just using echo
while you are reading the original input file (and never save the local demo.csv
on the server's disk). 您可以使用
readfile
或仅在读取原始输入文件时使用echo
来执行此操作(并且永远不要将本地demo.csv
保存在服务器磁盘上)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.