Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgetcsv() wrongly adds double-quotes to first element of first line

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?!?

like image 644
Dong3000 Avatar asked Apr 23 '15 15:04

Dong3000


2 Answers

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;
}
like image 117
Modder Avatar answered Sep 29 '22 05:09

Modder


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.

like image 38
Preciel Avatar answered Sep 29 '22 07:09

Preciel