I've found some strange thing converting csv file to an array and i can't figure it out why the $data_arr[0]["Name"] is undefined.
The $test_arr is created for comparison only, the expected result is printing $data_arr[0]["Name"] => Jeff
The code is:
// load the csv file & convert to an array
$csv_arr = array_map('str_getcsv', file('test.csv'));
// get the first index for the header
$header_arr = $csv_arr[0];
// new array for the data
$data_arr = [];
// skip the first line (header)
for ($i = 1; $i < count($csv_arr); $i++) {
for ($h = 0; $h < count($header_arr); $h++) {
// data_arr[0][key] = value ...
$data_arr[$i - 1][$header_arr[$h]] = trim($csv_arr[$i][$h]);
}
}
// create a test array
$test_arr = [];
// add the same data to the array as the original
$test_arr[0] = [
"Name" => "Jeff",
"Business" => "Google"
];
$test_arr[1] = [
"Name" => "Bill",
"Business" => "Microsoft"
];
// test arr print
print_r($test_arr);
print_r($test_arr[0]["Name"]);
// output: Jeff
// original array print
print_r($data_arr);
print_r($data_arr[0]["Name"]);
// output: null - Undefined index: Name
$test_arr printed:
Array
(
[0] => Array
(
[Name] => Jeff
[Business] => Google
)
[1] => Array
(
[Name] => Bill
[Business] => Microsoft
)
)
$data_arr printed:
Array
(
[0] => Array
(
[Name] => Jeff
[Business] => Google
)
[1] => Array
(
[Name] => Bill
[Business] => Microsoft
)
)
The test.csv file content:
Name,Business
Jeff,Google
Bill,Microsoft
I've tested the code under laravel tinker
It looks like the problem is the .csv file was saved with UTF-8 BOM encoding, with UTF8 encoding (without BOM) it works as expected.
There is my solution to remove the BOM in my code:
// load the csv file & convert to an array
$csv_arr = array_map('str_getcsv', file('test.csv'));
// remove BOM
$csv_json = json_encode($csv_arr, JSON_UNESCAPED_UNICODE);
$csv_json = str_replace("\xEF\xBB\xBF",'',$csv_json);
$csv_arr = json_decode($csv_json, true);