PHP array with value returns NULL

I have an array that is converted from a CSV file. I have two keys ID and NAME.

If I show the key name NAME, everything is fine. But when I tried to get the key identifier, I always get NULL, but the key identifier matters.

enter image description here

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"
}

Reset CSV

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
)
+4
source share
1 answer

The problem here is taken from the specification .

Invisible characters are added at the beginning of the file, so they are attached to the "ID" key, so PHP cannot find the ID key and displays NULL values.

Convert the CSV file to UTF-8 without specification, and it will fix your problem.

+5
source

All Articles