Last active
March 19, 2021 16:44
-
-
Save zkelo/35f91a82eb29d6d43a88f4472e7f9789 to your computer and use it in GitHub Desktop.
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 | |
// Название столбца, по значению которого нужно разбивать файлы | |
$splitColumn = 'Источник'; | |
// Название входного файла | |
$filename = 'in.csv'; | |
// Папка, в которую будут сохранятся файлы | |
$outDir = 'out'; | |
/* Код */ | |
if (!file_exists($outDir)) { | |
mkdir($outDir); | |
} | |
$splitColumnIndex = 0; | |
$headers = []; | |
$out = []; | |
$outExtension = pathinfo($filename, PATHINFO_EXTENSION); | |
$in = fopen($filename, 'r'); | |
while ($row = fgetcsv($in)) { | |
static $first = true; | |
if ($first) { | |
$splitColumnIndex = array_search($splitColumn, $row); | |
if ($splitColumnIndex === false) { | |
throw new Exception('В файле нет столбца, по которому необходимо делать разбивку'); | |
} | |
$headers = $row; | |
$first = false; | |
continue; | |
} | |
$writeHeaders = false; | |
$outName = &$row[$splitColumnIndex]; | |
if (!isset($out[$outName])) { | |
$out[$outName] = fopen($outDir . DIRECTORY_SEPARATOR . $outName . '.' . $outExtension, 'w'); | |
$writeHeaders = true; | |
} | |
$handler = &$out[$outName]; | |
if ($writeHeaders) { | |
fputcsv($handler, $headers); | |
} | |
fputcsv($handler, $row); | |
} | |
array_walk($out, function ($handler) { | |
fclose($handler); | |
}); | |
fclose($in); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment