簡體   English   中英

如何將php文件復制到csv文件並下載?

[英]How to copy a php file to a csv file and download it?

我想將整個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

如果caldataprog.php生成CSV並且您要復制結果,則可以執行以下操作:

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

您正在將輸出數據寫入服務器上名為demo.csv的文件,並且正在瀏覽器中下載名為demo.csv的文件,但它們不是同一文件

如果要在瀏覽器中下載文件,則需要PHP輸出文件的內容。

您可以使用readfile或僅在讀取原始輸入文件時使用echo來執行此操作(並且永遠不要將本地demo.csv保存在服務器磁盤上)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM