Add a new line to a CSV file

前端 未结 4 1532
心在旅途
心在旅途 2020-12-24 04:57

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?

4条回答
  •  温柔的废话
    2020-12-24 05:33

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

提交回复
热议问题