stevenreid Posted June 22, 2007 Share Posted June 22, 2007 My problem is I can't find info on how to take information from a specific line of a CSV. I have a CSV file with various products, I want to be able to select a particular line in the CSV to pick information out about that specific product. CSV is formated: Silver Bangle, 12.50, 7, Solid Silver Gold Bangle, 25.50, 8, Gold Plate here's my simple bit of script: $products = fopen("lphearts.csv", "r"); $thisproduct = fgetcsv($products, 1000, ","); $row = $_GET['item']; -- I know this doesn't actually 'do' anything but it's taking the item number from a querystring for now $item = $thisproduct[0]; $price = $thisproduct[1]; $stock = $thisproduct[2]; $description = $thisproduct[3]; fclose($products); so how can I get php to go to the particular line requested by the querystring and pass the relevant details to the strings? Hope this all makes sense - been trying to figure this one out for hours to no avail… Cheers! Link to comment https://forums.phpfreaks.com/topic/56653-solved-selecting-a-row-in-a-csv/ Share on other sites More sharing options...
sasa Posted June 22, 2007 Share Posted June 22, 2007 try $products = fopen("lphearts.csv", "r"); while ($thisproduct = fgetcsv($products,1000,',')) $out[] = $thisproduct; $row = $_GET['item']; $thisproduct = $out[$row]; $item = $thisproduct[0]; $price = $thisproduct[1]; $stock = $thisproduct[2]; $description = $thisproduct[3]; fclose($products); Link to comment https://forums.phpfreaks.com/topic/56653-solved-selecting-a-row-in-a-csv/#findComment-279811 Share on other sites More sharing options...
spfoonnewb Posted June 22, 2007 Share Posted June 22, 2007 <?php //Which line number would you like to display? ($_GET['item'] $line_number = "2"; //Get the file contents $content = file_get_contents("test.csv"); //Split each new-line, and create an array $line = preg_split("/\n/", $content); //Split individual data $data = preg_split("/,/", $line[$line_number-1]); //Fill the variables $item = $data[0]; $price = $data[1]; $stock = $data[2]; $description = $data[3]; //Example echo $item; /* --test.csv-- Silver Bangle, 12.50, 7, Solid Silver Gold Bangle, 25.50, 8, Gold Plate */ ?> Link to comment https://forums.phpfreaks.com/topic/56653-solved-selecting-a-row-in-a-csv/#findComment-279836 Share on other sites More sharing options...
stevenreid Posted June 22, 2007 Author Share Posted June 22, 2007 Excellent help thanks - both solutions are very admirable - would have thought there'd be a simple 'pick row' but guess not Link to comment https://forums.phpfreaks.com/topic/56653-solved-selecting-a-row-in-a-csv/#findComment-280033 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.