【问题标题】:Split a big txt file with php [closed]用php分割一个大的txt文件[关闭]
【发布时间】:2012-09-13 12:29:47
【问题描述】:

我有一个超过 100 万行的大 txt 文件 (84mb)。

我想将它拆分为单独的 50k 行文件。我该怎么做?我在网上搜索,但我没有找到任何关于它的信息。

【问题讨论】:

  • 这个之前已经回答过了……我觉得你应该看看stackoverflow.com/a/10271542/1226894
  • @Baba 我检查了给我的答案,但对我没有帮助。
  • 是什么让它与你想要的不同......

标签: php split


【解决方案1】:

这是我的脚本的修改版本:Read through huge text files and store each line in database

用法

set_time_limit(0);

// Split by Byte
splitData("b.php", __DIR__ . "/test", 1024 * 50); //Split 50Kb

// Split By line
splitLine("b.php", __DIR__ . "/test", 50000);

函数

function splitData($filename, $destination, $chunkSize) {
    $pathInfo = pathinfo($filename);
    $handle = fopen($filename, 'rb');
    $counter = 0;
    if ($handle === false) {
        return false;
    }
    while ( ! feof($handle) ) {
        $counter ++;
        $filePart = $destination . DIRECTORY_SEPARATOR . $pathInfo['filename'] . "_" . $counter . "." . $pathInfo['extension'];
        touch($filePart);
        file_put_contents($filePart, fread($handle, $chunkSize));
    }
    $status = fclose($handle);
    return $status;
}

function splitLine($filename, $destination, $lineSize) {
    $pathInfo = pathinfo($filename);
    $handle = fopen($filename, 'rb');
    $counter = 0;
    $splitCount = 0;
    if ($handle === false) {
        return false;
    }

    $content = "";
    while ( ($buffer = fgets($handle, 4096)) !== false ) {
        $content .= $buffer;
        $counter ++;

        if ($counter >= $lineSize) {
            $splitCount ++;
            $filePart = $destination . DIRECTORY_SEPARATOR . $pathInfo['filename'] . "_" . $splitCount . "." . $pathInfo['extension'];
            touch($filePart);
            file_put_contents($filePart, $content);
            $content = "";
            $counter = 0;
        }
    }
    $status = fclose($handle);
    return $status;
}

【讨论】:

    【解决方案2】:
    <?php 
    $handle = @fopen("/tmp/inputfile.txt", "r");
    $maxLines = 50;
    if ($handle) {
        $counter = 1;
        $fileCount = 1;
        $data = array();
        while (($buffer = fgets($handle, 4096)) !== false) {
            $data[] = $buffer;
            if(count($data) % $maxLines == 0) {
                file_put_contents("filename{$fileCount}.txt", implode("\n\r", $data));
                $data = array();
                $fileCount++;
            }
            $counter++;
        }
        if (!feof($handle)) {
            echo "Error: unexpected fgets() fail\n";
        }
        fclose($handle);
    }  
    ?>
    

    类似的方法应该可以工作,尽管我绝不会推荐它,但它不是解决问题的好方法。

    【讨论】:

    • 为什么要在4096 处加盖?只需留下参数,它就会处理任意长度的行。另外,设置$maxLines=50000 而不是50
    • 这会丢弃文件末尾的所有“奇数”行。在while之外添加另一个输出文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    相关资源
    最近更新 更多