将大型文本文档拆分为多个较小的文本文件

时间:2016-05-26 02:36:33

标签: php if-statement for-loop switch-statement fwrite

我正在使用fwrite()开发文本收集引擎来编写文本,但我想在写入过程中设置1.5 MB的文件大小上限,所以如果文件大于1.5mb,它将开始编写新文件文件从它停止的地方依此类推,直到它将源文件的内容写入多个文件。我有Google搜索,但许多教程和示例对我来说太复杂了,因为我是一名新手程序员。下面的代码位于for循环中,用于获取文本($RemoveTwo)。它不能按我的需要工作。任何帮助将不胜感激。

        switch ($FileSizeCounter) {
            case ($FileSizeCounter> 1500000):
                 $myFile2 = 'C:\TextCollector/'.'FilenameA'.'.txt';
                 $fh2 = fopen($myFile2, 'a') or die("can't open file");
                    fwrite($fh2, $RemoveTwo);
                    fclose($fh2);  
                break;
            case ($FileSizeCounter> 3000000):
                 $myFile3 = 'C:\TextCollector/'.'FilenameB'.'.txt';
                 $fh3 = fopen($myFile3, 'a') or die("can't open file");
                    fwrite($fh3, $RemoveTwo);
                    fclose($fh3);  
                break;
            default:
                echo "continue and continue until it stops by the user";
        }

1 个答案:

答案 0 :(得分:0)

尝试做这样的事情。您需要从源读取然后逐个写入,同时检查来自源的文件结尾。比较最大值和缓冲区值时,如果它们是true,则关闭当前文件并使用自动递增的数字打开一个新文件:

/*
** @param $filename [string] This is the source
** @param $toFile [string] This is the base name for the destination file & path
** @param $chunk [num] This is the max file size based on MB so 1.5 is 1.5MB
*/
function breakDownFile($filename,$toFile,$chunk = 1)
    {
        // Take the MB value and convert it into KB
        $chunk      =   ($chunk*1024);
        // Get the file size of the source, divide by kb
        $length     =   filesize($filename)/1024;
        // Put a max in bits
        $max        =   $chunk*1000;
        // Start value for naming the files incrementally
        $i          =   1;
        // Open *for reading* the source file
        $r          =   fopen($filename,'r');
        // Create a new file for writing, use the increment value
        $w          =   fopen($toFile.$i.'.txt','w');
        // Loop through the file as long as the file is readable
        while(!feof($r)) {
            // Read file but only to the max file size value set
            $buffer =   fread($r, $max);
            // Write to disk using buffer as a guide
            fwrite($w, $buffer);
            // Check the bit size of the buffer to see if it's
            // same or larger than limit
            if(strlen($buffer) >= $max) {
                // Close the file
                fclose($w);
                // Add 1 to our $i file
                $i++;
                // Start a new file with the new name
                $w  =   fopen($toFile.$i.'.txt','w');
           }
        }
        // When done the loop, close the writeable file
        fclose($w);
        // When done loop close readable
        fclose($r);
    }

使用:

breakDownFile(__DIR__.'/test.txt',__DIR__.'/tofile',1.5);