3

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.

4
  • So just use fwrite? Commented Sep 27, 2017 at 15:08
  • 1
    Share with us your code to see what you have tried so far. Commented Sep 27, 2017 at 15:08
  • @Michael Thanks! It Worked Commented Sep 27, 2017 at 15:18
  • This question could do with more detail and context to get sensible answers. Why is writing one line at a time not an option? How many is multiple; 2 lines, 200 million lines? Commented Sep 27, 2017 at 15:40

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

stream_copy_to_stream() might be even better
1

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);

Comments

-4

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.