Read a CSV file…

I will now profess my undying love for php. I have a project at work where I have to read a CSV file into an array. I thought it was going to take an endless amount of time to try and figure out how to do that. But PHP has done it all for me with this function fgetcsv and shows how it works with this snippet. Read and print the entire contents of a CSV file

<?php
$row = 1;
$handle = fopen (”test.csv”,”r”);
while ($data = fgetcsv ($handle, 1000, “,”)) {
$num = count ($data);
print “<p> $num fields in line $row: <br>\n”;
$row++;
for ($c=0; $c < $num; $c++) {
print $data[$c] . “<br>\n”;
}
}
fclose ($handle);
?>

*smooch*

3 Responses to “Read a CSV file…”

  1. Daynah Says:

    PHP is wonderful isn’t it? ^_^

  2. Mike Says:

    Actually, it’s not much more difficult in other languages. What you want is some sort of split or tokenize function. Java has a class (java.util.StringTokenizer, I believe) that handles breaking up strings based on a particular separator - in this case, a comma. In ASP (VB, really) there is - if I remember - a split() function that will break up a string based on a separator.

    PHP is nice because so many functions are built in - but it’s that same thing that annoys me sometimes. I often program in PHP not by logic but by hunting for a function that does what I want.

  3. dave Says:

    nice! thx