Zac
Zac

Reputation: 740

Remove extra comma after string

I have a lot of data in a CSV file. I wrote some code to extract only column 1 and put it in a txt file:

fwrite($file2, $data[0].',');

Now, this created a TXT file with all values separated by a comma. However, after the last value was read there was an extra comma

I don't need this, because when I used foreach($splitcontents as $x=> $y) using a comma delimiter, it reads a garbage value at the end because of the extra comma.

How do I remove or avoid the comma at the end?

Upvotes: 0

Views: 478

Answers (3)

Mark Eirich
Mark Eirich

Reputation: 10114

One way to solve the problem is to use rtrim($data, ',') on the data you load from the second file before splitting it. This will remove the trailing comma.

If you want to fix the file itself, you can do this:

ftruncate($file2, ftell($file2)-1);

You have to do this just before you call fclose()

Upvotes: 1

mario
mario

Reputation: 145512

Instead of assembling the CSV file yourself field-wise you could use fputcsv() which puts it into the right format:

while (...) {
    fputcsv($file2, array($data[0], $data[1], $data[22])  );

The second parameter must be an array. If you really only want one column, then leave out the rest.

Also for reading the files back in, check out fgetcsv(). This might simplify your foreach + $splitstring approach.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799390

Use fputcsv() instead of misreimplementing it.

Upvotes: 1

Related Questions