tags:

views:

62

answers:

1
+1  Q: 

parse csv file php

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

I want to be able to have the column names be 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 the first instance (not the column name) would display for column1.

How would I do that?

+1  A: 

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];
}
codaddict
I have tried fgetcsv but it doesn't put it into the column name arrays.
keith
I've added more details.
codaddict
Thanks for the reply. It is not really doing what I hoped. Is there a way for it to know the first line in the csv are the column names and each line after that are the rows? And the commas separate each column for each row?
keith
Before you run the loop to extract the rows, extract just the first row as header.
codaddict
How would I get the first row? It only looks at commas right? And the count of matrix is 66 in my case but there are more than that on the first line. Do you know why it stopped? Is there a limit on something or would quotes mess it up or something?
keith
@keith No offense, but how about reading the API docs and try a bit on your own instead of asking people to write the code for you. Also, how to handle CSV files has been asked and answered quite often on SO, so why not use the Search function for some examples.
Gordon
Good point @Gordon as well as a great example @codaddict
Phill Pafford
I'm sorry everyone for being ignorant on the matter. I have read over the manual for fgetcsv and I have done searches for the subject in SO. You see the examples I have seen do not work with my data so that is why I was asking. I'm thinking now that maybe it is my data or computer that is the issue. I'm on a Mac. Apparently there is an issue with fgetcsv and Mac's and new lines...I added ini_set('auto_detect_line_endings',TRUE); and still not working. I also read that it has problems with quotes in the data. Some of my data has quotes and others do not. My csv is generated by Google Docs.
keith