在CSV文件中添加新行

时间:2012-07-09 16:24:18

标签: php csv

如果我在服务器上保存了CSV,我如何使用PHP编写给定的行,在其底部说142,fred,elephants

4 个答案:

答案 0 :(得分:85)

打开CSV文件以追加(fopen­Docs):

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

然后添加您的行(fputcsv­Docs):

fputcsv($handle, $line); # $line is an array of string values here

然后关闭手柄(fclose­Docs):

fclose($handle);

我希望这有用。

答案 1 :(得分:10)

您可以为文件使用面向对象的接口类 - 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;

答案 2 :(得分:1)

此解决方案适用于我:

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

参考:https://www.w3schools.com/php/func_filesystem_fputcsv.asp

答案 3 :(得分:0)

如果您希望每个拆分文件保留原始标题;这是hakre答案的修改版本:

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