I am messing about with CSV files inside a console command for laravel. I am aware there are libraries for importing CSV files, however i have came across a strange undefined index error i am hoping someone may have more information about. I can achieve what i need without this column, but i am curious as to why this error is occurring.
public function handle()
{
$file = Storage::disk('local')->get('upload.csv');
$lines = explode("
", $file);
$keys = [];
foreach ($lines as $key => $line)
{
$outputLine = [];
if($key == 0)
{
// Get header columns
$keys = str_getcsv($line); continue;
}
// Get row contents
$items = str_getcsv($line);
foreach ($items as $k => $item)
{
// Rename keys to match headers
$outputLine[$keys[$k]] = $item;
}
// try to access $outputLine['id']
// error: Undefined Index: id
$csv[$key] = $outputLine;
}
}
However output of $csv[$key]
clearly shows the key ['id'] for all entries in the csv. Trying to access here also throws the same issue. Accessing any other arbitrary key in the array works fine. It is always the first key, regardless of name.
UPDATE: Providing example of CSV import
id,name,email,membership_id
1,John,John@example.com,1
2,Jane,Jane@example.com,2
3,Brian,Brian@example.com,3
UPDATE 2: Providing dump of $items
array:4 [
0 => "1"
1 => "John"
2 => "john@example.com"
3 => "1"
]
array:4 [
0 => "2"
1 => "Jane"
2 => "jane@example.com"
3 => "2"
]
array:4 [
0 => "3"
1 => "Brian"
2 => "brian@example.com"
3 => "3"
]
array:4 [
0 => "4"
1 => "Adam"
2 => "adam@example.com"
3 => "4"
]
array:4 [
0 => "5"
1 => "Frank"
2 => "frank@example.com"
3 => "5"
]
array:4 [
0 => "6"
1 => "Phil"
2 => "phil@example.com"
3 => "6"
]
DUMP OF $outputLine
array:4 [
"id" => "1"
"name" => "John"
"email" => "john@example.com"
"membership_id" => "1"
]
array:4 [
"id" => "2"
"name" => "Jane"
"email" => "jane@example.com"
"membership_id" => "2"
]
array:4 [
"id" => "3"
"name" => "Brian"
"email" => "brian@example.com"
"membership_id" => "3"
]
array:4 [
"id" => "4"
"name" => "Adam"
"email" => "adam@example.com"
"membership_id" => "4"
]
array:4 [
"id" => "5"
"name" => "Frank"
"email" => "frank@example.com"
"membership_id" => "5"
]
array:4 [
"id" => "6"
"name" => "Phil"
"email" => "phil@example.com"
"membership_id" => "6"
]