Well, old news ? yeah but still effective and is required on many occasions. A few days back while working on a large sports betting website project, I was provided more than 20 .csv files with a minimum of 8-15 columns in each file and minimum of 400 entries in each file, containing the data of Seasons, Leagues, Divisions, Teams, Match dates and their goals etc. I had to first collect all the teams and then add that data to my other specific tables for teams, seasons, goals etc etc. So for that I had to write a function to grab data from a .csv file

I needed a function in which I could just pass the file name and tell the number of coloumns to be fetched, so below is teh code that you can use if you want somethign similar.

how to use function
$arr = csv2array(”filename.csv”, 7); # 7 means read 7 columns only

here is the fulle .php code to be used and printing the final array..

<?

 #Microsoft Excel 5 Header and End Of File Binary Representation
 define(”XLSFile_Header”, pack(”s*”,2057,8,0,0,0,0));
 define(”XLSFile_End”,  pack(”s*”,10,0));

 

$arr = csv2array(”filename.csv”, 7); # 7 means read 7 colums only
print_r($arr); // display array

 

 function csv2array($file,$columns=false) {
 
  $ret = Array();

  $handle = fopen ($file,”r”);
  $row=-1;
  $fields = Array();
  
  while ($data = fgetcsv ($handle, 1000, “,”)) {
   if($columns)
    $data = array_slice($data,0,$columns);
   $row++;
   if(emptyCsvRow($data)) continue;
   if($row == 0) {
    #format fields
    $fields = $data;
    continue;
   }
   $ret []= indexArray($fields,$data);
   
  }
  fclose ($handle);
  return $ret;
 }
 
 function indexArray($fieldsArr,$dataArr) {
  $ret= Array();
  foreach($fieldsArr as $k=>$v) {
   $ret[$v] = $dataArr[$k];
  }
  return $ret;
 }
 
 function emptyCsvRow($row) {
  foreach($row as $v) {
   if(trim($v) != “”) {
    return false;
   }
  }
  return true;
 } 

?>