Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array with value returns NULL

Tags:

arrays

php

csv

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
)
like image 632
3y3skill3r Avatar asked May 15 '15 00:05

3y3skill3r


1 Answers

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.

like image 150
Benoit Esnard Avatar answered Sep 25 '22 02:09

Benoit Esnard