6

I have a very curious issue whith fgtcsv(). Look at this code

  $csv_check = fopen(CSV_DIR.$this->db_table.".csv","r");
  $data = fgetcsv($csv_check, 1000, $this->fields_terminated_by);
  fclose($csv_check);

A print_r($data) outputs the following:

array (
0 => '"program_id"',
1 => 'program_name',
2 => 'program_logo',
)

Curiously, $data[0] is double-quoted here... The original line in this CSV file looks like this:

"program_id";"program_name";"program_logo"

I don't get it at all... Counting the chars of $data[0] with strlen($data[0]) returns 15, even if wrongly quoted, it must be 12 chars... I'm very stunned...!

Any ideas?!?

Dong3000
  • 556
  • 1
  • 4
  • 21
  • 3
    Does the csv file have a BOM header? If so, then it's likely being treated as part of the data, which means that the quotes are also part fo the data because the first quote occurs after the BOM header, so isn't considered an enclosure quote – Mark Baker Apr 23 '15 at 15:54
  • That's it, @MarkBaker. Thx! – Dong3000 Apr 23 '15 at 16:11
  • Just encountered this problem. What's a BOM header? How did you solve this? – Dustin Graham Sep 17 '15 at 20:25
  • @DustinGraham &others... -> [What's different between UTF-8 and UTF-8 without BOM?](http://stackoverflow.com/questions/2223882/whats-different-between-utf-8-and-utf-8-without-bom) – gmo Feb 29 '16 at 15:57

2 Answers2

4

From PHP.net notes:

When a BOM character is suppled, fgetscsv may appear to wrap the first element in "double quotation marks". The simplest way to ignore it is to progress the file pointer to the 4th byte before using fgetcsv.

<?php

// BOM as a string for comparison.
$bom = "\xef\xbb\xbf";

// Read file from beginning.
$fp = fopen($path, 'r');

// Progress file pointer and get first 3 characters to compare to the BOM string.
if (fgets($fp, 4) !== $bom) {
    // BOM not found - rewind pointer to start of file.
    rewind($fp);
}

// Read CSV into an array.
$lines = [];
while (!feof($fp) && ($line = fgetcsv($fp)) !== false) {
    $lines[] = $line;
}
Modder
  • 751
  • 9
  • 14
1

I know this is an old topic, but as someone may come like me and try to figure out a solution, here is how to fix it.

Open notepad (in my case, I used notepad++) and create a new file.
Copy/paste all the data in the new file.
Save it as "All type" and add ".csv" yourself.
The file should be saved without BOM, and you can process with reading your CSV file with PHP.

Preciel
  • 1,949
  • 1
  • 13
  • 37