5

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.

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

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
)
5
  • 8
    How about including the actual code, rather than teeny pictures of it? Commented May 15, 2015 at 0:16
  • Also... var_dump($category) . . . The whole darned thing, as PHP sees it. Or, heck, var_dump($array). Commented May 15, 2015 at 0:27
  • Can you show the content of your CSV file please ? Commented May 15, 2015 at 0:31
  • 1
    My guess is there's a space in the ID heading. Commented May 15, 2015 at 0:32
  • No, i have same content, what is here. I converted CSV to UTF-8 in Notepad, cause it's exported from excel and i need good encoding of special chars Commented May 15, 2015 at 0:39

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You are right, thank you! You saved my deathline. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.