How to Write Multiple Rows/Arrays to CSV File in one attempt using PHP? [closed]

北城余情 提交于 2019-12-05 22:01:00

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!