Stonep123
Stonep123

Reputation: 625

how to use fgetscsv with a csv file to parse the file into an array using PHP

ok so ive been trying to get this to work for hours now and cant figure it out. Ive got a csv file in the format of

item 1, item 1 stuff
item 2, item 2 stuff
item 3, item 3 stuff
item 4, item 4 stuff

and im trying to parse it into an array using fgetscsv.

$file = fopen('test.csv', 'r');
    while (($MyCSVArray = fgetcsv($file)) !== FALSE) {

    print_r($MyCSVArray);
}
fclose($file);

I would really rather parse it into an associative array so i can index it like so

MyCSVArray[item 1]

which would output

item 1 stuff

However the problem I am having is that since there isnt a comma after every value it groups item 1 stuff with item 2 like so

MyCSVArray[0] = item 1
MyCSVArray[1] = item 1 stuff item 2
MyCSVArray[2] = item 2 stuff item 3

Maybe I dont understand csv files or the csv function, but I really need this to work the way I want and dont understand how to make it work and am about to smash my face into my keyboard.

Upvotes: 1

Views: 477

Answers (1)

Mike Brant
Mike Brant

Reputation: 71422

Just read the data like you are and set the value into a new associative array as desired

$new_array = array()
$file = fopen('test.csv', 'r');
while (($MyCSVArray = fgetcsv($file)) !== FALSE) {
    $new_array[$MyCSVArray[0]] = $MyCSVArray[1];
}
fclose($file);

var_dump($new_array);

To the second part of your problem, it seems like you might not have proper end of line characters in your file if items from the next row are being grouped with the items from previous row.

Upvotes: 1

Related Questions