Add a new line to a CSV file

PhpCsv

Php Problem Overview


If I have a CSV saved on a server, how can I use PHP to write a given line, say 142,fred,elephants to the bottom of it?

Php Solutions


Solution 1 - Php

Open the CSV file for appending (fopen­Docs):

$handle = fopen("test.csv", "a");

Then add your line (fputcsv­Docs):

fputcsv($handle, $line); # $line is an array of strings (array|string[])

Then close the handle (fclose­Docs):

fclose($handle);

Solution 2 - Php

You can use an object oriented interface class for a file - SplFileObject http://php.net/manual/en/splfileobject.fputcsv.php (PHP 5 >= 5.4.0)

$file = new SplFileObject('file.csv', 'a');
$file->fputcsv(array('aaa', 'bbb', 'ccc', 'dddd'));
$file = null;

Solution 3 - Php

This solution works for me:

<?php
$list = array
(
'Peter,Griffin,Oslo,Norway',
'Glenn,Quagmire,Oslo,Norway',
);

$file = fopen('contacts.csv','a');  // 'a' for append to file - created if doesn't exit

foreach ($list as $line)
  {
  fputcsv($file,explode(',',$line));
  }

fclose($file); 
?>

Ref: https://www.w3schools.com/php/func_filesystem_fputcsv.asp

Solution 4 - Php

If you want each split file to retain the headers of the original; this is the modified version of hakre's answer:

$inputFile = './users.csv'; // the source file to split
$outputFile = 'users_split';  // this will be appended with a number and .csv e.g. users_split1.csv

$splitSize = 10; // how many rows per split file you want 

$in = fopen($inputFile, 'r');
$headers = fgets($in); // get the headers of the original file for insert into split files 
// No need to touch below this line.. 
    $rowCount = 0; 
    $fileCount = 1;
    while (!feof($in)) {
        if (($rowCount % $splitSize) == 0) {
            if ($rowCount > 0) {
                fclose($out);
            }
            $out = fopen($outputFile . $fileCount++ . '.csv', 'w');
            fputcsv($out, explode(',', $headers));
        }
        $data = fgetcsv($in);
        if ($data)
            fputcsv($out, $data);
        $rowCount++;
    }
    
    fclose($out);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDamonView Question on Stackoverflow
Solution 1 - PhphakreView Answer on Stackoverflow
Solution 2 - PhpelshnkhllView Answer on Stackoverflow
Solution 3 - PhpwebdevfreakView Answer on Stackoverflow
Solution 4 - PhpLewisView Answer on Stackoverflow