parse csv file php
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 na开发者_开发知识库me. 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?
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];
}
精彩评论