Jump to content

[SOLVED] Selecting a row in a .CSV


stevenreid

Recommended Posts

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

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);

<?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
*/

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.