I've never worked with csv files before and I'm hoping to create arrays in php from the columns.
So for example the csv would look something like this:
Name, Address, DOB
john doe, 22 grove street, 06,06,2006
i'd like each of the columns to be an array named by the column headings. Any time I parse the file(test.csv) i get arrays of the table rows instead.
Following code will do the work for you. And you can see the real working script of the exactcode at this url:
http://sugunan.net/demo/csv1.php
$i=0;
$filename = 'data1.csv';
$contents = file($filename);
foreach($contents as $line) {
$line = preg_replace( "/\r|\n/", "", $line );
$line_array = explode(",",$line);
if($i==0)
{
foreach($line_array as $key=>$val)
{
$csv_heading[$key] = trim($val);
}
}
else
{
foreach($line_array as $key=>$val)
{
$csv_array[$i][$csv_heading[$key]] = $val;
}
}
$i++;
}
print_r($csv_array);
data file url: http://sugunan.net/demo/data1.csv
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.