保存CSV文件而不是下载

时间:2015-06-05 10:55:59

标签: php mysql csv

所以我有这段代码从mysql数据库生成一个CSV文件。但是,它下载代码而不是将其保存到目录以供进一步使用(需要通过phpmailer发送该文件)。 我应该做些什么更改才能将文件保存到目录中。

$array = array();
if(file_exists('records_monthly.csv'))
    {
        unlink('records_monthly.csv');
    }
# Headers
$array[] = array("Serial Number","Donation Type", "Amount", "Status", "Date", "Orderref", "DIN");
$serial=1;
try
{
    $s = $conn->query("SELECT c.firstname AS firstname, c.lastname as lastname, c.address AS address, c.city AS city, c.postalnumber AS postalnumber, c.email AS cemail, d.donation_type as donation_type, d.donation_amount as donation_amount, d.orderref as orderref, d.status as status, d.donation_on AS donation_on, d.din as din from customers c, donations d where c.email = d.donator");
}
catch(PDOException $e)
{
    echo $e->getMessage();
}
while($donations = $s->fetch(PDO::FETCH_OBJ))
{
    if($donations->status == 0)
    {
        $array[] = array($serial++,$donations->donation_type,$donations->donation_amount,"Failed",$donations->donation_on,$donations->orderref,$donations->din);    
    }
    else
    {
        $array[] = array($serial++,$donations->donation_type,$donations->donation_amount,"Success",$donations->donation_on,$donations->orderref,$donations->din);
    }

}

array_to_csv_download($array,"records_monthly.csv",",");

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    // open raw memory as file so no temp files needed, you might run out of memory though
    $f = fopen('php://memory', 'w'); 
    // loop over the input array
    foreach ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
    // rewind the "file" with the csv lines
    fseek($f, 0);
    // tell the browser it's going to be a csv file
 header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
   header('Content-Disposition: attachement; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
   fpassthru($f);
}

1 个答案:

答案 0 :(得分:0)

直接写入指定文件而不是php://memory,不要将标题和输出发送到浏览器

function array_to_csv_without_download($array, $filename = "export.csv", $delimiter=";") {
    $f = fopen($filename, 'w'); 
    // loop over the input array
    foreach ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
   fclose($f);
}