Jump to content

Splitting contents of file up to multiple files


devWhiz

Recommended Posts

ok so say I have a file with .. this information in one file

 

548402354 7e99c2c49be0ad1a95fd3b4a2f65fc941e9cf194
548402225 9e0b2788f21a317eb76159f3e0c4e4a090492f2a
548402329 1aa382935c94d73f58bdb3203686cc0124fb3443
548402596 c41655fa8f14346cbd8a656a18ecb82caa3c1f9c
548402535 558e1ee14f2423681668a168a3980304ac54bd15
548402456 48ee03332c417cab51eaec13b415fde8c0b6a641
548400202 5bf3400e3c074eb8b42a962dc7e60777d2b2848a
548400842 cc672d4785ec5b9e22db7b60e203286c840c4f37
548400682 547c8ac38243b0f9a94609177d0dd12194059aa5
548400810 54afebbb3e884fea5563c017b18dd390ff1ff034
548400581 ec7305326b5514cbf05ab4a78647ed756da9db55
548400431 b3dcaa272c759ebe4e5b00053ef390b21b23f60c

 

and I want to take and split the contents into 6 different files..

 

So it would take the first 2 lines and write to filename 1.txt, then it would take the 2 lines after that and write a file named 2.txt, so on and so forth

 

Any help is appreciated, thanks

 

 

Link to comment
Share on other sites

One way:

<?php
$orig = file('orig_file.txt');
$new = array();
$new[] = 'dmy';
for($i=0;$i<count($orig);$i += 2) {
$new[] = array($orig[$i],$orig[$i+1]);
}
for ($i=1;$i<count($new);++$i) {
file_put_contents($i . '.txt',implode('',$new[$i]));
}
?>

 

Ken

Link to comment
Share on other sites

hmm what I would edit if I wanted to make it in sets of 110?

 

Ive tried

 

<?php
$orig = file('330AM.txt');
$new = array();
$new[] = 'dmy';
for($i=0;$i<count($orig);$i += 110) {
$new[] = array($orig[$i],$orig[$i+1]);
}
for ($i=1;$i<count($new);++$i) {
file_put_contents($i . '.txt',implode('',$new[$i]));
}
?>

Link to comment
Share on other sites

Here's another way using array_slice()

<?php
$orig = file('330AM.txt');
$new = array();
$new[] = 'dmy';
$slice_size = 110;
for($i=0;$i<count($orig);$i += $slice_size) {
   $new[] = array_slice($orig,$i,$slice_size);
}
for ($i=1;$i<count($new);++$i) {
file_put_contents($i . '.txt',implode('',$new[$i]));
}
?>

 

Now if you want to change the size of each new file, you just have to change the variable $slice_size.

 

Ken

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.