Created
July 28, 2023 11:26
-
-
Save zkelo/3ad2a037dfead30617178950df858b3d to your computer and use it in GitHub Desktop.
Script that splits one CSV into different CSV's by row count and stores results in `out` directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$filename = 'in.csv'; | |
$outDir = 'out'; | |
$in = fopen($filename, 'r'); | |
$out = []; | |
$outName = pathinfo($filename, PATHINFO_FILENAME) . '_'; | |
$extension = pathinfo($filename, PATHINFO_EXTENSION); | |
$first = true; | |
$fileNum = 1; | |
$rowNum = 1; | |
$rowsPerFile = 500; | |
if (file_exists($outDir)) { | |
exec('rm -rf ' . escapeshellarg($outDir)); | |
} | |
mkdir($outDir); | |
$out[$fileNum] = fopen(implode(DIRECTORY_SEPARATOR, [ | |
$outDir, | |
$outName . $fileNum . '.' . $extension | |
]), 'w'); | |
$headers = []; | |
while ($row = fgetcsv($in)) { | |
if ($first) { | |
$headers = $row; | |
$first = false; | |
fputcsv($out[$fileNum], $headers); | |
continue; | |
} | |
if ($rowNum > $rowsPerFile) { | |
fclose($out[$fileNum]); | |
if (!isset($out[++$fileNum])) { | |
$out[$fileNum] = fopen(implode(DIRECTORY_SEPARATOR, [ | |
$outDir, | |
$outName . $fileNum . '.' . $extension | |
]), 'w'); | |
fputcsv($out[$fileNum], $headers); | |
} | |
$rowNum = 1; | |
} | |
fputcsv($out[$fileNum], $row); | |
$rowNum++; | |
} | |
fclose($out[$fileNum]); | |
fclose($in); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment