0

I have a csv like this:

A,1
B,2
C,3
D,4
e,5
...

How do I append a "," before each new line - and then split the file after every second element?

so that I get: A,B,C,D,E ... in one file and 1,2,3,4,5 ... in another?

fopen, fgetcsv and fputcsv I get - but in between?

theduck
  • 2,589
  • 13
  • 17
  • 23
Tontaube
  • 39
  • 6
  • 1
    Just read the whole thing in a two-dimensional array, and then use array_column … and write the two resulting arrays back into individual files. – 04FS Sep 30 '19 at 12:56
  • Unless the file is HUGE and blows your memory limit – RiggsFolly Sep 30 '19 at 12:57
  • Why do you want to append a comma before each new line? – ascsoftw Sep 30 '19 at 13:01
  • A little confused !! Your _so that I get:_ example does not seem to match with your requirement _How do I append a "," before each new line - and then split the file after every second element_ – RiggsFolly Sep 30 '19 at 13:04
  • I think he's making it harder than it has to be and making it one giant comma separated string and trying to split it up that way. – Lulceltech Sep 30 '19 at 13:08
  • 1
    @Lulceltech: yes, you´re right! – Tontaube Sep 30 '19 at 13:15

1 Answers1

0

Small file, just put it in an array as suggested.

Large file? Then read here how you can open a large file: Reading very large files in PHP

Did 2 tests with a 1.3GB file and a 9.5GB File.

1.3 GB

Using fopen()

This process used 15555 ms for its computations.

It spent 169 ms in system calls.

Using file()

This process used 6983 ms for its computations.

It spent 4469 ms in system calls.

9.5 GB

Using fopen()

This process used 113559 ms for its computations.

It spent 2532 ms in system calls.

Using file()

This process used 8221 ms for its computations.

It spent 7998 ms in system calls.

Seems file() is faster.

Now process the file line by line. For every line, just use:

$linearr = explode(",",$line);

Now add $line[0] to the end of outputfile 1 and $line[1] to the end of outputfile 2.

Two ways to do the appending are described here: Create or write/append in text file

$txt = "user id date";  
$myfile = file_put_contents('logs.txt',$txt.PHP_EOL , FILE_APPEND | LOCK_EX);

or

$myfile = fopen("logs.txt", "a") or die("Unable to open file!"); 
$txt = "user id date"; 
fwrite($myfile, "\n". $txt); 
fclose($myfile);
Lulceltech
  • 1,662
  • 11
  • 22
Rick
  • 806
  • 7
  • 15