Page 1 of 1

Can't figure out CSV import

Posted: Wed May 28, 2008 11:42 pm
by Mr Tech
I'm trying to import a CSV file into a website using php but I can't figure it out...First of all my code... which I got from the php.net website...

Code: Select all

   $file = 'test.csv';
 
    $fp = fopen($file, 'r');
    if (!$fp) {
        $err = 1;
    }
 
    $length = filesize($file) + 1;
 
    $filecontents = array();
 
    while (($line = fgetcsv($fp, $length, ",")) !== FALSE) {
        $filecontents[] = $line;
    }
    fclose($fp);
The problem is that the whole CSV file is put into the one array instead of breaking each line up into its own array. How do I achieve that?

Re: Can't figure out CSV import

Posted: Thu May 29, 2008 12:02 am
by Christopher
Each line should be an array. You should end up with an array or arrays. Use print_r() to show the data.

Re: Can't figure out CSV import

Posted: Thu May 29, 2008 12:31 am
by Mr Tech
That's what I thought... however, when it puts it into an array, it doesn't start a sub array when a new line begins... For example... this is how it should look (not sure if I've formatted it correctly but I'm sure you'll get the idea):

Code: Select all

Array
(
    Array [0]
    (
        [0] => Item ID
        [1] => Name
    )
    Array [1]
    (
        [0] => 1
        [1] => Ben
    )
    Array [2]
    (
        [0] => 2
        [1] => Sarah
    )
    Array [3]
    (
        [0] => 3
        [1] => Daniel
    )
)
This is how it looks with my code:

Code: Select all

Array
(
    [0] => Item ID
    [1] => Name
    [2] => 1
    [3] => Ben
    [4] => 2
    [5] => Sarah
    [6] => 3
    [7] => Daniel
)