PHP文件到浏览器的CSV文件

时间:2013-12-16 21:04:59

标签: php csv

我正在使用fwrite创建一个将输出到浏览器的csv文件。我得到一个空白页面,但是当我转储我的数组时,数组将显示出来。 这是我的代码:

$result = Camp::getAllCampers($camp);

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

$fh = fopen('export.csv', 'w');

foreach ($result as $product) {
    $person = $product['Person'];
    $club = $product['Club'];
    $type = $product['Type'];
    $registeredby = $product['RegisteredBy'];
    $registereddate = $product['RegisteredDate'];
    $event1 = $product['Event1'];
    $event2 = $product['Event2'];
    $event3 = $product['Event3'];
    $event4 = $product['Event4'];

    fwrite($fh, "{$person},{$club}\n");
}

fclose($fh); 

2 个答案:

答案 0 :(得分:2)

你几乎就在那里,你只是错过了readfile()调用,将你刚刚创建的文件发送到浏览器。

答案 1 :(得分:0)

这是我想出的:

$result = Camp::getAllCampers($camp);

function makeCSV($table){
    $csv="";foreach($table as $r){$csv .= implode(",", $r).",\n";}return $csv;
}

$new_file_name = 'export.csv';

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename='.$new_file_name);
echo makeCSV($result);