如何使用PHP一次尝试将多个行/数组写入CSV文件?
问题描述:
我必须在csv文件中写入多个记录.我正在使用php的fputcsv函数,该函数将数组作为一行并写入文件中.这样,每一行将有多个写入操作.
I have to write multiple records in csv file. I'm using fputcsv function of php which take array as one row and write it in the file. In this way there will be multiple write operations for each row.
我正在寻找一种方法,可以通过一次写入操作将多行记录到csv文件中.
I'm looking for a method with which I can write multiple rows in one write operation to csv file.
请帮助.
答
解决方案1: 将数据保存为String,然后使用 fwrite !
代码:
$file = 'test.csv';
$file = fopen($file, 'w');
$content = '';
for($i=0;$i<10;$i++){
$content.="a,b,c,d\r\n";
}
fwrite($file, $content);
fclose($file);
解决方案2: ,如@chiliNUT所建议的那样,使用输出缓冲区.
Solution 2: as suggested by @chiliNUT using output buffer.
代码:
$handle = fopen("php://output", "w");
$data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
ob_start();
foreach ($data as $dat) {
fputcsv($handle, $dat);
}
$csvContent = ob_get_clean();
file_put_contents("csv.csv", $csvContent);