Can't figure out CSV import

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Can't figure out CSV import

Post 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?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Can't figure out CSV import

Post by Christopher »

Each line should be an array. You should end up with an array or arrays. Use print_r() to show the data.
(#10850)
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Re: Can't figure out CSV import

Post 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
)
Post Reply