Forum Moderators: coopster

Message Too Old, No Replies

Getting Specific Fields from a CSV

Can I use fgetcsv?

         

inuwolf

1:38 pm on Feb 21, 2006 (gmt 0)

10+ Year Member



I've been using fgetcsv to populate an HTML table with CSV data and so far it has been working great. But now I'm looking to call specific data from the table (ie: row 3, column 5), and I'm not sure fgetcsv can be used for this. Every online example of its use involves getting all the CSV data from a file as my table has done.

What function should I use to get specific fields from my CSV? My table doesn't use unique ids, at least not like mysql, with a unique number identifying each row in the leftmost column. What then should I use to identify each row from which I'd like to get data?

I'm making a page that describes a person based on the query string and the information in the database, in which each person has a row. So example.com/example.php?christopher+walken would bring up a page where Walken's information is listed. So I guess the ideal way to do what I want is to query the CSV for the name in the query string (Christopher Walken), then get and print the other information in the row (tall, great guy, etc). Any suggestions on this query?

dmorison

1:47 pm on Feb 21, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You just need a loop to read rows until you find the one you want; and then break out of the loop.

In your case; it looks like you want to read the file until a certain field contains a certain value. For example, if then name is in field 3 and you're looking for the "Christopher Walken" record, you would do something like this:


$found = false;

$fp = fopen("filename.csv","r");

while($record = fgetcsv($fp))
{
// quit the loop when you find the record you want
if ($record[3] == "Christopher Walken") { $found = true; break; }
}

fclose($fp);

if ($found)
{
// display $record here
}
else
{
print "Not found!";
}

Replace "Chrisopher Walken" with $_GET["name"] (if you're using?name= on your URL) and you should be in business...

inuwolf

8:36 pm on Feb 21, 2006 (gmt 0)

10+ Year Member



Thanks dmorison, that works perfectly!