每x行拆分文本文件

时间:2014-01-20 15:42:09

标签: php string text

如何根据行数将一个文本文件拆分为单独的文件?例如,文本文件有10000行,我希望有5个单独的文件,每个文件有2000行。

我试过这个:Split a text file in PHP

基本上我想要一个类似的解决方案,但是通过计算行数而不是字节数。

谢谢!

- edit-- 我按照@ 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);
}

?>

2 个答案:

答案 0 :(得分:2)

像这样简单:

$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);
}

//未经测试。

答案 1 :(得分:0)

我不知道这是多么有效,或者它是否会起作用,但至少它会给你一个很好的起点:

<?php

// get file contents into string
$stringData = file_get_contents('MyTextFile.txt');

// split by newline
$arrayData = split('\r\n', $stringData);

// loop through arrayData
for ($i = 0; $i < count($arrayData); $i++)
{
    $file = 'myFileName';
    $fileCount = 1;
    // for every 2000 lines, create a new file
    if ($i % 2000 == 0)
    {
        $fileCount++;
    }
    file_put_contents($file . $fileCount . '.txt', $arrayData[$i], FILE_APPEND | LOCK_EX);
}

?>
  • 未经测试的代码。