0

I am almost embarrassed to ask this, but I've been trying to accomplish this task for a few hours now. Without a thorough grasp of the fopen or fgetcsv functions, I'm a bit lost. Each example I find does not quite work for me.

I'm seeking a way to load each line of a CSV file into one array. For example, if this is my CSV file:

Apple,Banana,Orange
Kiwi,Watermelon,Pineapple
Dog,Cat,Bird

Then this would be my array:

Array
(
    [0] => Apple,Banana,Orange
    [1] => Kiwi,Watermelon,Pineapple
    [2] => Dog,Cat,Bird
)

I'd appreciate any tips. Thanks! :)


Just for reference, this is what I have so far:

$list = '../reports/apples.csv';

$csvfile = fopen($list,'rb');
while(!feof($csvfile)) {
$listofthings[] = fgetcsv($csvfile);
}
fclose($csvfile);

print_r($listofthings);

However, this is producing a multidimensional array as follows, when I'd rather just have one big array.

Array
(
    [0] => Array
        (
            [0] => Apple
            [1] => Banana
            [2] => Orange
        )

    [1] => Array
        (
            [0] => Kiwi
            [1] => Watermelon
            [2] => Pineapple
        )

    [2] => Array
        (
            [0] => Dog
            [1] => Cat
            [2] => Bird
        )
)

3 Answers3

2

If you want to break the file up by lines, use file.

$newArray = file('/path/to/file.csv');

If you want each comma-delimited value as an element of the array, use file_get_contents and explode by a comma.

$contents = file_get_contents('/path/to/file.csv');
$newArray = explode(',', $contents); 
Nick Pickering
  • 3,095
  • 3
  • 29
  • 50
  • 1
    I noticed the same thing when you first answered and Googled the solution. "\n" worked. Then I came and saw you answered with the same thing! Hah. Marking as solution - this worked for me, and I knew it was going to be something extremely simple. Thanks! –  Feb 23 '13 at 04:36
1

You could explode after reading the file as Nicholas suggests or you could hit it all at once with file:

$lines = file('/path/to/file.csv');
prodigitalson
  • 60,050
  • 10
  • 100
  • 114
0

are looking for this ??

$mytext = "Apple,Banana,Orange
Kiwi,Watermelon,Pineapple
Dog,Cat,Bird";

$line_explode = explode("\n", $mytext);
$comma_explode = array();
foreach ($line_explode as $line) {
  $comma_explode[] = explode(",", $line);
}

print_r($comma_explode);

Output

Array
(
    [0] => Array
        (
            [0] => Apple
            [1] => Banana
            [2] => Orange
        )

    [1] => Array
        (
            [0] => Kiwi
            [1] => Watermelon
            [2] => Pineapple
        )

    [2] => Array
        (
            [0] => Dog
            [1] => Cat
            [2] => Bird
        )

)
Dino Babu
  • 5,814
  • 3
  • 24
  • 33