Search code examples
phpcsvtrim

Trimming special characters from a CSV file


I have a CSV file with the content below:

1,a,,
255,,b,
255,,,c

This is my code to parse the file:

$fp = @fopen('1.csv','rb');
while (!feof($fp)){
  $data = fgets($fp, 4096);
  $data = rtrim($data, ',');
  echo $data.'<br>';
}

The result is the same as the original file. I don't know why? The follow content is what I want:

1,a
255,,b
255,,,c

Solution

  • You forgot about line end chars

    Try

    rtrim($data, "\n\r,");