64

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?

1
  • 2
    That's called appending see the mode when you open a file, there often is open for appending with file-system functions.
    – hakre
    Jul 9, 2012 at 16:26

4 Answers 4

132

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);
4
  • 3
    @fvu: Not really. The + is not necessary, a alone creates the file as well if it does not exists. The + is for reading support. See "'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it." de.php.net/manual/en/function.fopen.php
    – hakre
    Jul 9, 2012 at 16:30
  • 4
    @Dale: Wasn't meant that way. Added a more trivializing final sentence that can not be read too wrong that easily. Not to hurt anybodies feelings here.
    – hakre
    Jul 9, 2012 at 17:01
  • Would help if you included that $line needs to be an array of strings, rather than the actual line itself.
    – Overcode
    May 29, 2015 at 17:44
  • 1
    @Overcode: For the line itself use fputs / fwrite - in case you want to write one record, terminate it with newline ("\n") as that character normally separates records in UNIX textfiles.
    – hakre
    May 29, 2015 at 20:45
12

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

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.