59

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

4

4 回答 4

122

打开 CSV 文件进行附加 ( 文档):fopen

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

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

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

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

fclose($handle);
于 2012-07-09T16:28:15.630 回答
12

您可以对文件使用面向对象的接口类 - 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;
于 2015-12-24T16:26:16.723 回答
3

这个解决方案对我有用:

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

于 2017-09-13T13:26:19.353 回答
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);
于 2017-05-02T12:41:21.947 回答