用php创建csv文件

时间:2013-03-19 13:55:51

标签: php csv

我想创建一个csv文件,但是当我运行代码时,它返回一个银行页面而没有csv文件。我使用PHP 5。 我使用以下代码:

<?php
    $data = array ('aaa,bbb,ccc,dddd',
                   '123,456,789',
                   '"aaa","bbb"');

    $fp = fopen('data.csv', 'w');
    foreach($data as $line){
             $val = explode(",",$line);
             fputcsv($fp, $val);
    }
    fclose($fp);
?>

谢谢!

4 个答案:

答案 0 :(得分:85)

它是空白的,因为您正在写信file。你应该使用output写信给php://output,并发送标题信息以表明它是csv。

示例

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
        'aaa,bbb,ccc,dddd',
        '123,456,789',
        '"aaa","bbb"'
);

$fp = fopen('php://output', 'wb');
foreach ( $data as $line ) {
    $val = explode(",", $line);
    fputcsv($fp, $val);
}
fclose($fp);

答案 1 :(得分:39)

@ Baba的答案很棒。但您不需要使用explode,因为fputcsv将数组作为参数

例如,如果您有三列,四行文档,这是一个更直的版本:

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');

$user_CSV[0] = array('first_name', 'last_name', 'age');

// very simple to increment with i++ if looping through a database result 
$user_CSV[1] = array('Quentin', 'Del Viento', 34);
$user_CSV[2] = array('Antoine', 'Del Torro', 55);
$user_CSV[3] = array('Arthur', 'Vincente', 15);

$fp = fopen('php://output', 'wb');
foreach ($user_CSV as $line) {
    // though CSV stands for "comma separated value"
    // in many countries (including France) separator is ";"
    fputcsv($fp, $line, ',');
}
fclose($fp);

答案 2 :(得分:0)

以防万一有人想将CSV文件保存到电子邮件附件的特定路径。然后可以完成以下操作

我知道我已经为新手添加了很多评论:)

我添加了一个示例,以便您可以很好地进行总结。

$activeUsers = /** Query to get the active users */

/** Following is the Variable to store the Users data as 
    CSV string with newline character delimiter, 

    its good idea of check the delimiter based on operating system */

$userCSVData = "Name,Email,CreatedAt\n";

/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user ) {
    $userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
}
/** Here you can use with H:i:s too. But I really dont care of my old file  */
$todayDate  = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName   = 'Active Users '.$todayDate.'.csv';
$filePath   = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file

/** Just in case if I run the script multiple time 
    I want to remove the old file and add new file.

    And before deleting the file from the location I am making sure it exists */
if(file_exists($filePath)){
    unlink($filePath);
}
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */
fclose($fp);

/** Now you can send email with attachments from the $filePath */

注意:以下是增加 memory_limit 时间限制,但我只是为了确保是否有人面临连接超时或其他任何问题。 坚持使用之前,请确保找到其他选择。

您必须在上述脚本的开头添加以下内容。

ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');

答案 3 :(得分:-1)

我希望这个例子对您有用

$data= "Sr. No.,Vendor Name,Cargo Type,Amount,Delivery Address,Pickup Time,Delivery Time\n";

        $i = 1;
        if(!empty($detail)) {
            foreach ($detail as $list) {

                $data .= $i.",";
                $data .= any data
                $data .= any data
                $data .= any data
                $data .= any data
                $data .= any data
                $data .= any data
                $data .="\n";
                $i++;

            }
        }

        header("Content-Type: application/csv");
        $csv_filename = 'anyfilename.xlsx';
        header("Content-Disposition:attachment;filename=".$csv_filename);
        $fd = fopen ($csv_filename, "wb");
        fputs($fd,$data);
        fclose($fd);
        echo $data;
        die();