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?
Use fputcsv()
instead of misreimplementing it.
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.
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()
精彩评论