Search code examples
phpfilecsvfile-handlingfputcsv

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


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.


Solution

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