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?!?
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 usingfgetcsv
.
<?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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With