php 向 CSV 文件添加新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11399197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:26:49  来源:igfitidea点击:

Add a new line to a CSV file

phpcsv

提问by Damon

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

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

回答by hakre

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

打开要附加的 CSV 文件 ( 文档):fopen

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

Then add your line (fputcsv­Docs):

然后添加您的行(文档):fputcsv

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

Then close the handle (fclose­Docs):

然后关闭手柄(文档):fclose

fclose($handle);

I hope this is helpful.

我希望这是有帮助的。

回答by elshnkhll

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)

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

回答by webdevfreak

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

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

回答by Lewis

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

如果您希望每个拆分文件都保留原始文件的标题;这是 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);