Skip to content

Instantly share code, notes, and snippets.

@euperia
Created May 26, 2017 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save euperia/ea6c84f43250e01353ae559cf6aabf18 to your computer and use it in GitHub Desktop.
Save euperia/ea6c84f43250e01353ae559cf6aabf18 to your computer and use it in GitHub Desktop.
Split a CSV file into chunks
#!/usr/bin/env php
<?php
function help() {
echo PHP_EOL . 'Usage: csvsplitter <input file> <number of lines>' . PHP_EOL;
exit();
}
if (!isset($argv[1])) {
echo PHP_EOL . "Please enter a csv filename";
help();
}
if (substr($argv[1], -3) != 'csv') {
echo PHP_EOL . "Please enter a valid csv file";
help();
}
if (false === isset($argv[2]) || false === filter_var($argv[2], FILTER_VALIDATE_INT)) {
echo PHP_EOL . "Please enter a valid number for lines to split";
help();
}
$inputFile = $argv[1];
$outputFile = explode('.', $inputFile)[0];
$splitSize = $argv[2];
$rowCount = 0;
$fileCount = 1;
$in = fopen($inputFile, 'r');
$header = '';
while (!feof($in)) {
if ($rowCount == 0) {
$header = fgetcsv($in);
}
if (($rowCount % $splitSize) == 0) {
if ($rowCount > 0) {
fclose($out);
}
$out = fopen($outputFile . '_' . $fileCount++ . '.csv', 'w');
fputcsv($out, $header);
}
$data = fgetcsv($in);
if ($data) {
fputcsv($out, $data);
}
$rowCount++;
}
fclose($out);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment