here is my csv
column1,column2,column3,column4,column5
column1_row1,column2_row1,column3_row1,column4_row1,column5_row1
column1_row2,column2_row2,column3_row
For reading it all at once you can use:
$csv = array_map("str_getcsv", file("file1.csv",FILE_SKIP_EMPTY_LINES));
$keys = array_shift($csv);
To turn all the rows into a nice associative array you could then apply:
foreach ($csv as $i=>$row) {
$csv[$i] = array_combine($keys, $row);
}
Can't you just do one fgetcsv
call first to get the headers, and then start a loop to get the rest?
Modified the example found in the manual. It should write out a table with headers and values following.
<?php
$row = 1;
if (($handle = fopen('test.csv', 'r')) !== FALSE)
{
echo '<table>';
// Get headers
if (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
{
echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';
}
// Get the rest
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
{
echo '<tr><td>'.implode('</td><td>', $data).'</td></tr>';
}
fclose($handle);
echo '</table>';
}
?>
try using str_getcsv — Parse a CSV string into an array
it should solve ur prob...
// Opening the file for reading...
$fp = fopen('path_to_your_file.csv', 'r');
// Headrow
$head = fgetcsv($fp, 4096, ';', '"');
// Rows
while($column = fgetcsv($fp, 4096, ';', '"'))
{
// This is a great trick, to get an associative row by combining the headrow with the content-rows.
$column = array_combine($head, $column);
echo $column['column1'];
}
I modified first answer to better handle different column separators
if (($handle = fopen("hdbsource/products_stock.csv", "r")) !== FALSE) {
while (($csv[] = fgetcsv($handle, 1000, ',')) !== FALSE) {}
fclose($handle);
}
$keys = array_shift($csv);
foreach ($csv as $i=>$row) {
$csv[$i] = array_combine($keys, $row);
}
It looks like it might be taking it all as one line. Perhaps your csv has a different line ending than it should have? At least that's what it looks like in your output. If you look at row 1, column 5 in your result array, it contains a line ending and column 1 in row 2. And the same in the rest. It reads it all in as one line.
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem. -- fgetscv
What platform are you on? Either way, check the line endings.