I have an array which is converted from CSV file. I have there two keys ID and NAME.
If I show key NAME everything is OK. But when i tried to get key ID, i always get NULL but key ID have value set.
function convertCsvToArray($filename='', $delimiter=';')
{
if(!file_exists($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$array = convertCsvToArray('/path/to/csv/categories.csv',';');
/*
$array structure is
array(2){
["ID"] => 3
["NAME"] => Some name
}
*/
foreach($array as $category){
var_dump($category["ID"]); //return NULL
var_dump($category["NAME"]); //return "Some name"
}
CSV dump
ID;NAME
3;Značkové nealko nápoje
4;Nízkoenergetické nápoje
5;Minerálne vody, sóda
6;Tetrapack 0.2l a 0.5l
print_r for $array
Array
(
[0] => Array
(
[ID] => 3
[NAME] => Značkové nealko nápoje
)
[1] => Array
(
[ID] => 4
[NAME] => Nízkoenergetické nápoje
)
)
print_r for $category
Array
(
[ID] => 3
[NAME] => Značkové nealko nápoje
)
The problem here comes from BOM .
Invisible characters are added at the begining of the file, so they are prefixed to the "ID" key, so PHP can't find the ID key, and shows NULL values.
Convert your CSV file to UTF-8 without BOM and it will fix your problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.