1

I am having problems reading a CSV file where the values are encapsulated in quotes.

The first line of my CSV file are headers and they look like the following:

"Header 1","Header 2","Header 3","Header 4","Header 5"

When using fgetcsv, the first header retains the surrounding quotes.

while (($row = fgetcsv($file, 6000, ',')) !== false)
{
    echo '<pre>';
    print_r($row);
    echo '</pre>';
    exit;
}

This outputs the following to the page

Array
(
    [0] => "Header 1"
    [1] => Header 2
    [2] => Header 3
    [3] => Header 4
    [4] => Header 5
)

Does anyone have any advice on how to make sure the quotes are not included in the first array item?

Thanks

Typhoon101
  • 2,063
  • 8
  • 32
  • 49
  • `fgetcsv()` has an optional "enclosure" parameter. https://secure.php.net/manual/en/function.fgetcsv.php – brombeer Sep 19 '18 at 11:57
  • I can't reproduce this behavior with http://php.net/manual/en/function.str-getcsv.php, maybe try pulling in the 6000 records and then use the string function? – user3783243 Sep 19 '18 at 12:27
  • 1
    Does your file have a BOM? AFAIK, this is a known problem with UTF-8 BOMs, see [this comment](http://php.net/manual/en/function.fgetcsv.php#122696). See also [this bug report](https://bugs.php.net/bug.php?id=63433). – Karsten Koop Sep 19 '18 at 12:35

1 Answers1

0

As Karsten Koop as a comment stated, it's probably due to a utf8 BOM character. And since php is not solving this behaviour, you'll need to get rid of that char before opening the csv-file for reading.

i.e. using a function like this (more info):

public static function removeUtf8Bom($fileUri){
    $content = file_get_contents($fileUri);
    $content = str_replace("\xEF\xBB\xBF",'',$content);
    file_put_contents($fileUri,$content);
}
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Siebe Jongebloed
  • 3,906
  • 2
  • 14
  • 19