28

here is my csv

column1,column2,column3,column4,column5
column1_row1,column2_row1,column3_row1,column4_row1,column5_row1
column1_row2,column2_row2,column3_row2,column4_row2,column5_row2
column1_row3,column2_row3,column3_row3,column4_row3,column5_row3
column1_row4,column2_row4,column3_row4,column4_row4,column5_row4
column1_row5,column2_row5,column3_row5,column4_row5,column5_row5
column1_row6,column2_row6,column3_row6,column4_row6,column5_row6
column1_row7,column2_row7,column3_row7,column4_row7,column5_row7
column1_row8,column2_row8,column3_row8,column4_row8,column5_row8
column1_row9,column2_row9,column3_row9,column4_row9,column5_row9

first row is the column names of course. i tried fgetcsv() but all that would do is display all rows. rather than what i want. how can i do it?

so if i were to put the data into an array at the end i would be able print out a table format of the data just like its shown in excel.

thanks

this is my sample:

$filename = "upload/sample.csv";
if (($handle = fopen($filename, 'r')) !== FALSE)
{
    while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) 
    {
       print_r($row);
     }
}

this is my output: (i put the $row into a pre so i can show it)

Array
(
    [0] => column1
    [1] => column2
    [2] => column3
    [3] => column4
    [4] => column5
column1_row1
    [5] => column2_row1
    [6] => column3_row1
    [7] => column4_row1
    [8] => column5_row1
column1_row2
    [9] => column2_row2
    [10] => column3_row2
    [11] => column4_row2
    [12] => column5_row2
column1_row3
    [13] => column2_row3
    [14] => column3_row3
    [15] => column4_row3
    [16] => column5_row3
column1_row4
    [17] => column2_row4
    [18] => column3_row4
    [19] => column4_row4
    [20] => column5_row4
column1_row5
    [21] => column2_row5
    [22] => column3_row5
    [23] => column4_row5
    [24] => column5_row5
column1_row6
    [25] => column2_row6
    [26] => column3_row6
    [27] => column4_row6
    [28] => column5_row6
column1_row7
    [29] => column2_row7
    [30] => column3_row7
    [31] => column4_row7
    [32] => column5_row7
column1_row8
    [33] => column2_row8
    [34] => column3_row8
    [35] => column4_row8
    [36] => column5_row8
column1_row9
    [37] => column2_row9
    [38] => column3_row9
    [39] => column4_row9
    [40] => column5_row9
)
4
  • What's wrong with using fgetcsv and then walking through each line?
    – Pekka
    Commented Apr 15, 2011 at 8:23
  • can you show me a sample of your method? then i'll point out what confuses me
    – Exploit
    Commented Apr 15, 2011 at 8:24
  • I don't really have a sample. Can you show yours and what doesn't work?
    – Pekka
    Commented Apr 15, 2011 at 8:25
  • Does it help if you set the enclosure (which defaults to ") to something else? Like null or an empty string or something like that?
    – Svish
    Commented Apr 15, 2011 at 11:36

6 Answers 6

86

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);
}
5
  • 1
    How can I use this with a ; as seperator?
    – Michiel
    Commented Jul 9, 2013 at 10:22
  • This way you cannot deal with line breakers in a cell.
    – Michael
    Commented Oct 14, 2014 at 4:34
  • 4
    @Michiel, how to use a different separator: $file = file("file1.csv",FILE_SKIP_EMPTY_LINES); $csv = array_map("str_getcsv",$file, array_fill(0, count($file), ';'));
    – Tapper
    Commented Jan 4, 2015 at 17:26
  • 1
    @mario this falls into my favorite category of answers. short, works as advertised and most important it teaches me new functionality
    – pzirkind
    Commented Nov 13, 2015 at 17:50
  • 2
    Note this only works if all of your data rows are the same length as the header row. Commented Feb 22, 2018 at 21:31
8
// 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'];
}
6
  • i tried your sample but i didnt get an output. know why that would be?
    – Exploit
    Commented Apr 15, 2011 at 8:41
  • only works if your column-names are 'column1', 'column2', etc. like in your example. echo $column['the_name_of_your_column_in_the_headrow'];
    – Fidi
    Commented Apr 15, 2011 at 8:48
  • yea i did , nothing came out so i did a print_r of $column and nothing . here is the pastie pastie.org/1796761
    – Exploit
    Commented Apr 15, 2011 at 8:58
  • Do you have error_reporting enabled? If not, do it and look if an error occurred. do you reach the while loop? paste an die(x); for debugging into the loop to see if it is executed. If not, the file is empty or the filepointer ($fp) is not set (e.g. invalid path).
    – Fidi
    Commented Apr 15, 2011 at 9:32
  • Good solution for anyone stuck on pre 5.3
    – Cups
    Commented Apr 8, 2013 at 11:00
1

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

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>';
}
?>
2
  • @Sarmen: Added sample. haven't tested it though. let me know if it works.
    – Svish
    Commented Apr 15, 2011 at 8:33
  • ps i added what i was attempting.
    – Exploit
    Commented Apr 15, 2011 at 8:36
0

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.

0

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);
}
1
  • This didn't work for me. Commented May 10, 2023 at 15:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.