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



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

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";
}

试着做这样的事情。您需要从源代码中读取,然后逐段写入,同时检查源代码中的文件结尾。当您比较最大值和缓冲区值时,如果它们是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);

最新更新