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