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.
I'm looking for a method with which I can write multiple rows in one write operation to csv file.
Please help.
Here's an example using the memory stream. It should give you a structure that you can customize to work through the buffer in pieces and reset progress if the buffer gets too big.
<?php
// Sample data
$arrData = array(
array("Fruit","Color","Calories"),
array("Apple","Red",95),
array("Orange","Orange",45),
array("Plum","Purple",45)
);
// Open output file
$fpOut = fopen("bufferedWrite.csv", "w");
// Write to memory stream
$msBuffer = fopen("php://memory","w+");
foreach($arrData as $arrRecord)
{
fputcsv($msBuffer, $arrRecord);
}
// Rewind back to the beginning of the buffer and save the contents into a file in one big write
rewind($msBuffer);
fwrite($fpOut, stream_get_contents($msBuffer));
// Close the memory stream
fclose($msBuffer);
// Close the output file
fclose($fpOut);
If your worried about doing multiple write operations, you can "write" the csv to the output buffer, capture the output buffer with ob_start()
/ob_get_clean()
, then dump the buffer into a csv, like this:
<?php
$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);
Solution 1: Saving Data in String and then using fwrite worked!
Code:
$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);
Solution 2: as suggested by @chiliNUT using output buffer.
Code:
$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);
来源:https://stackoverflow.com/questions/46451299/how-to-write-multiple-rows-arrays-to-csv-file-in-one-attempt-using-php