Fgetcsv initial line reading
I'm working with a CSV file and PHP5 however I'm not quite understanding what I am seeing. The file is as follows when I open it in a text editor:
"Jun 23,2010 21:40","City1","Location1","0 0 0 "
"Jun 23,2010 21:41","City2","Location1","0 0 0 "
What I get as output from this code:
while (($data = fgetcsv($handle, 1000, ",","\"")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
Is this output:
5 fiel开发者_运维技巧ds in line 1:
"Jun 23
2010 21:40"
City1
Location1
0 0 0
4 fields in line 2:
Jun 23,2010 21:41
City2
Location1
0 0 0
As you can see, on the first line fgetcsv skips the enclosure character and reads the comma as the first field, whereas the 2nd line reads correctly and so do all the lines after that.
So am I missing something or is this a bug, and if it is a bug what would be some possible solutions other than rewriting the original file?
Your code (full):
<?
$handle = fopen('test.csv', "r");
while (($data = fgetcsv($handle, 1000, ",","\"")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
?>
Parses the data you posted above correctly:
taifun:test killerx$ php test.php
4 fields in line :
Jun 23,2010 21:40
City1
Location1
0 0 04 fields in line 1:
Jun 23,2010 21:41
City2
Location1
0 0 0
Maybe you have a "misencoded" " sign. like “” or ‟ or ˝. They may look similar, but are not the same thing as ".
I had the same problem. It came from encoding. I converted the CSV file in "UTF-8 without BOM" and it was solved.
I found this happens if the file is UFT8 encoded and contains BOM. A simple way around this issue is to forward the file pointer by 3 bytes after opening, then begin fetching lines for CSV:
$f = fopen('file.csv', 'r');
fread($f, 3);
while(($line = fgetcsv($f)) {
// do some stuff
}
精彩评论