【问题标题】:How to copy a php file to a csv file and download it?如何将php文件复制到csv文件并下载?
【发布时间】:2023-03-31 14:10:01
【问题描述】:

我想将整个 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 csv download copy


    【解决方案1】:

    我看到的是您最终将文件复制到其他文件并且最后没有刷新。

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

    如果 caldataprog.php 生成 CSV 并且你想复制结果,你可以这样做:

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

    【讨论】:

      【解决方案2】:

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

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

      您可以使用readfile 来执行此操作,或者在读取原始输入文件时仅使用echo(并且永远不要将本地demo.csv 保存在服务器磁盘上)。

      【讨论】:

        猜你喜欢
        • 2012-07-17
        • 2018-03-24
        • 1970-01-01
        • 2020-12-29
        • 2015-06-04
        • 1970-01-01
        • 2015-11-12
        • 2015-08-05
        • 2011-01-18
        相关资源
        最近更新 更多