【发布时间】:2014-08-11 10:22:05
【问题描述】:
需要使用php和linux将大型csv文件分行拆分成多个文件。
CSV 包含 -
"id","name","address"
"1","abc","this is test address1 which having multiple newline
separators."
"2","abc","this is test address2
which having multiple newline separators"
"3","abc","this is test address3.
which having multiple
newline separators."
我使用了 linux 命令 - split -l 5000 testfile。
但它无法以正确的格式拆分 csv,因为在 csv 中有一个字段地址具有多个换行符,因此命令从该行拆分文件。
我也尝试过使用 PHP:
$inputFile = 'filename.csv';
$outputFile = "outputfile";
$splitSize = 5000;
$in = fopen($inputFile, 'r'):
$header = fgetcsv($in);
$rowCount = 0;
$fileCount = 1;
while (!feof($in)) {
if (($rowCount % $splitSize) == 0) {
if ($rowCount > 0) {
fclose($out);
}
$filename = $outputFile . $fileCount++;
$out = fopen($filename .'.csv', 'w');
chmod($filename,777);
fputcsv($out, $header);
}
$data = fgetcsv($in);
if ($data) {
fputcsv($out, $data);
$rowCount++;
}
}
fclose($out);
如何解决这个问题?
【问题讨论】:
-
使用能够解析 CSV 的编程语言
-
我用php试过了,但是会花太多时间。有没有其他解决方案来解决这个问题?
-
PHP 应该很快。可以展示一下你用过的PHP代码吗?
-
请不要将代码作为评论发布,你看,它很难阅读。改为编辑您的问题。 (我为你做了,因为这是你的第一篇文章)
-
PHP 代码看起来不错,应该可以正常工作