php - 每 x 行分割文本文件

标签 php string text

如何根据行数将一个文本文件拆分为单独的文件?例如,文本文件有 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/

相关文章:

php - 使用 mysql 的带有子菜单的菜单

php - 更改具有相同 ID joomla 的模块标题之一的 ID

java - 错误: cannot find symbol (using replaceAll ) codenameone

php - 如何一次轻松地插入、更新或删除记录

php - 如何在 php 数组中插入多个 html 输入字段数据?

string - 人类可读的短单向哈希用于模糊日志文件中的字符串?

c++ - 在一个文件中创建一个字符串 vector 并在另一个文件中使用它

text - Haskell:在 ByteStrings 和不同的文本编码之间进行转换

node.js - 将存储在内存中的字符串传递给 pdftotext、antiword、catdoc 等

android - 如何在CheckedtextView中对齐右侧的复选框