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

Link to comment
Share on other sites

<?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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.