Skip to content

Instantly share code, notes, and snippets.

@riaf
Created October 9, 2013 09:20
Show Gist options
  • Save riaf/6898563 to your computer and use it in GitHub Desktop.
Save riaf/6898563 to your computer and use it in GitHub Desktop.
<?php
/**
* csv-split.php
*
* ```sh
* php csv-split.php -n 1000 -f input.csv
* ```
*
* @author Keisuke SATO <[email protected]>
*/
$options = getopt("n:f:H");
if (!isset($options['f'])) {
echo 'Usage: php csv-split.php -n 100 -f input.csv', PHP_EOL;
exit(1);
}
$filename = $options['f'];
$linelimit = $options['n'] ?: 100;
$hasHeader = isset($options['H']);
$header = [];
if (!file_exists($filename)) {
printf("`%s` is not found.\n", $filename);
exit(1);
}
$fp = fopen($filename, 'r');
if ($hasHeader) {
$header = fgetcsv($fp);
}
$basename = basename($filename, '.csv');
$i = 0;
$c = 0;
$tfp = null;
while (($data = fgetcsv($fp)) !== FALSE) {
if ($i == 0) {
if ($tfp) {
fclose($tfp);
}
$tfp = fopen(sprintf('%s_%03d.csv', $basename, ++$c), 'w');
if ($hasHeader) {
fputcsv($tfp, $header);
}
}
fputcsv($tfp, $data);
$i++;
if ($i > $linelimit) {
$i = 0;
}
}
if ($tfp) {
fclose($tfp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment