I am trying to read a CSV file using PHP. I want to use a while statement for each line, and would like to assign a variable for each column. The reason I am assigning variables for each column is so that I can use those variables within a sql query.
$csv = fopen('sample2.csv','r') or die("can't open file");
while($csv_line = fgetcsv($csv,1024)) {
//Not sure what to do here
}
fclose($csv) or die("can't close file");
I understand how to open the file and read the overall line, but not how to control the individual columns.
Updated Code
<?php
$csv = fopen('sample.csv','r') or die("can't open file");
while($csv_line = fgetcsv($csv,1024)) {
list($column1, $column2, $column3) = $csv_line;
echo 'Column 1: '.$column1.'<br />';
echo 'Column 2: '.$column2.'<br />';
echo 'Column 1: '.$column1.'<br />';
echo 'Column 3: '.$column3.'<br />';
}
fclose($csv) or die("can't close file");
?>
fgetcsvreturns an array with each field in it. You can use thelistfunction to get all columns in that array: