Luis Alvarado
Luis Alvarado

Reputation: 9406

Reading specific CSV value in PHP

I have the following CSV file:

08-0018421032;00-0018151831;G-20009429-0;G-20009429-0;0374048-0
27-001842101232;10-0018151831;G-30009429-0;G-50009429-0;7374048-0
36-0018421033232;20-0018151831;G-40009429-0;G-60009429-0;8374048-0

As you can see the separator is the ; symbol.

I then send this info to php via a jquery plugin which works perfect since I can read the file in PHP. The following code grabs the CSV file (Which is the $csvfile variable) and I can see the lines in it:

$file = fopen("upload/$csvfile", "r");
while (!feof($file) ) {
$line = fgetcsv($file, 1024,';');
print $line[0].'<br/>';
}
fclose($file);

What I need is to be able to select not only the line but on the value in it. To go to a specific value, for example in the first line the 3rd value would be G-20009429-0 and I would assign this to a php variable to be used later on.

Right now I have no idea how to grab a specific value in a line and also when I print the $line[0] it shows the values in a vertical order instead of a horizontal order. What I mean with this is that it shows the following output:

00-0018151831
10-0018151831
20-0018151831

Instead of showing me like this:

 08-0018421032;00-0018151831;G-20009429-0;G-20009429-0;0374048-0

Maybe is the sleep but am stuck here. Just to repeat, the csv file is read by Php correctly since I can do a print_r on it and it shows all the lines in it. The thing is how to manipulate the information after I have the csv and how to grab a specific value in a specific line. Thank you.

Upvotes: 0

Views: 224

Answers (1)

deceze
deceze

Reputation: 522382

$line is an array containing every element from that row. $line[0] is the first element of the row, $line[1] the second element and so on. Try var_dump($line). What you're doing is you output every first element of every row.

If you want to output every element in one line, just concatenate the array again:

echo join(';', $line);

But then that's missing the point of fgetcsv, which is specifically helpfully separating those elements into an array for you so you can work with them.

Upvotes: 1

Related Questions