Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse csv file php

Tags:

php

csv

I have a csv file that I want to use with php. The first thing in the csv are column names. Everything is separated by commas.

I want to be able to put the column names as the array name and all the values for that column would be under that array name. So if there were 20 rows under column1 then I could do column1[0] and the first instance (not the column name) would display for column1.

How would I do that?

like image 726
keith Avatar asked May 31 '26 02:05

keith


1 Answers

You want fgetcsv it will get each row of the CSV file as an array. Since you want to have each column into its own array, you can extract elements from that array and add it to new array(s) representing columns. Something like:

$col1 = array();
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
  $col1[] = $row[0];
}

Alternatively, you can read the entire CSV file using fgetcsv into a 2D matrix (provided the CSV file is not too big) as:

$matrix = array();
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
  $matrix[] = $row;
}

and then extract the columns you want into their own arrays as:

$col1 = array();
for($i=0;$i<count($matrix);$i++) {
  $col1[] = $matrix[0][i];
}
like image 80
codaddict Avatar answered Jun 01 '26 15:06

codaddict



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!