how do i parse a csv file to grab the column names first then the rows that relate to it?

家住魔仙堡 提交于 2019-11-28 04:45:12

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);
}
Alex Sawallich
// 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'];
}

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...

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.

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);
}

I made this quick solution using fgetcsv, works fine and it's easier to read and understand. Then the whole result is saved in the $csv array

$csv = array();
$i = 0;
if (($handle = fopen($upload['file'], "r")) !== false) {
    $columns = fgetcsv($handle, 1000, ",");
    while (($row = fgetcsv($handle, 1000, ",")) !== false) {
        $csv[$i] = array_combine($columns, $row);
        $i++;
    }
    fclose($handle);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!