Laravel 3创建文本(CSV)文件

时间:2013-05-21 15:29:09

标签: php csv laravel

您好我试图从数据库中获取所有电子邮件,然后将它们输出到文本(逗号分隔)文件中。这是我所做的但不起作用:

public function get_textfile() {

$emails = Staff::get('email');

header("Content-type: text/csv");  
header("Cache-Control: no-store, no-cache");  
header('Content-Disposition: attachment; filename="filename.txt"');

$stream = fopen("php://output", 'w');

foreach($emails as $email) {
fputcsv($stream, $email, ',');
}

fclose($outstream);     
}

return (something)?

得到这个:错误6(net :: ERR_FILE_NOT_FOUND):找不到文件或目录。

这是我的路线:

    Route::get('textfile', array('as' => 'textfile','uses' => 'admin@textfile'));

2 个答案:

答案 0 :(得分:0)

尝试file_put_contents($filename, implode(',', Staff::get('email')));

答案 1 :(得分:0)

将所有数据收集到一个字符串中,然后输出如下:

$data = '';
foreach ($emails as $email)
{
    // If you want 1 email per line
    $data .= '"'.$email.'"'.PHP_EOL;

    // If you want all emails on 1 line
    $data .= '"'.$email.'",';
}

header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=My Cool File.csv');
header('Pragma: no-cache');
header('Expires: 0');

echo $data;