如何根据行数将一个文本文件拆分为单独的文件?例如,文本文件有 10000 行,我想要 5 个单独的文件,每个文件有 2000 行。
我已经尝试过:Split a text file in PHP
基本上我想要一个类似的解决方案,但是通过计算行数而不是字节数。
谢谢!
--编辑-- 我按照@user1477388的提示让它工作了
<?php
// get file contents into string
$stringData = file_get_contents('MyTextFile.txt');
// split by newline
$arrayData = split("\n", $stringData);
$fileCount = 0;
// loop through arrayData
for ($i = 0; $i < count($arrayData); $i++)
{
$file = 'myFileName';
// for every 2000 lines, create a new file
if ($i % 2000 == 0)
{
$fileCount++;
}
file_put_contents($file . $fileCount . '.txt', $arrayData[$i]."\n", FILE_APPEND | LOCK_EX);
}
?>
最佳答案
像这样简单:
$in = file("file");
$counter = 0; // to void warning
while ($chunk = array_splice($in, 0, 2000)){
$f = fopen("out".($counter++), "w");
fputs($f, implode("", $chunk));
fclose($f);
}
//未测试。
关于php - 每 x 行分割文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21238127/