简体   繁体   中英

Splitting a text file in half using PHP?

I want to take one text file, split it in half, and put one half in one file, then the remaining half in the next. How would one accomplish this?

an example would be: split.php?n=file.txt

$file = $_GET['n'];

$i = 1;
$fp = fopen("./server/php/files/".$file,'a+');
$fs = filesize("./server/php/files/".$file);
$lengthhalf = $fs / 2;
while(! feof($fp)) {
    $contents = fread($fp,$lengthhalf);
    file_put_contents('./server/php/files/[2]'.$file,$contents);
    $i++;
}

This does the work, without reading the whole file (or half of it) at once in memory :

function split_in_halves($file, $half1, $half2) {
    $size = filesize($file);
    $fd = fopen($file, 'rb');

    stream_copy_to_stream($fd, fopen($half1, 'wb'), $size/2);
    stream_copy_to_stream($fd, fopen($half2, 'wb'));
}
split_in_halves('foo', '[1]foo', '[2]foo');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM