scriptygoddess

20 Mar, 2003

Read a CSV file…

Posted by: Jennifer In: Bookmarks

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

March 20th, 2003 at 12:06 pm

Avatar

PHP is wonderful isn't it? ^_^

2 | Mike

March 29th, 2003 at 10:49 pm

Avatar

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.

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements