Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将php文件复制到csv文件并下载?_Php_Csv_Download_Copy - Fatal编程技术网

如何将php文件复制到csv文件并下载?

如何将php文件复制到csv文件并下载?,php,csv,download,copy,Php,Csv,Download,Copy,我想将整个php文件复制到csv文件中并下载它,但是我得到的demo.csv文件是空的。为什么我得到一个空文件 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"'); /

我想将整个php文件复制到csv文件中并下载它,但是我得到的
demo.csv
文件是空的。为什么我得到一个空文件

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);
?>

我看到的是,您最终将一个文件复制到另一个文件,而不是最后刷新这个文件

<?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

您正在将输出数据写入服务器上名为
demo.csv
的文件,并在浏览器中下载名为
demo.csv
的文件,但它们不是同一个文件

如果要在浏览器中下载文件,需要让PHP输出文件的内容

您可以在读取原始输入文件时使用或仅使用
echo
(并且永远不要在服务器磁盘上保存本地
demo.csv

$source = 'http://yourwebsite.net/caldataprog.php';
$destination = 'demo.csv';
copy($source, $destination);