Thursday, February 14, 2019

Parsing CSV on PHP

This is a PHP function that you can use in parsing CSV that will return an array.

This will parse even a non Windows CSV format which is difficult to parse with hidden new lines.

Hope this helps a lot!

public function csvToArray($filename='', $delimiter=',') { 
  if (!file_exists($filename) || !is_readable($filename)) return FALSE;
  $header = ''; 
  $data = array(); 

  if (($handle = fopen($filename, 'r')) !== FALSE) :
    $tmpfile = fopen("$filename.tmp", 'w+');
    while(!feof($handle)) {
      $line = trim(fgets($handle));
      $lines = preg_split("(\r|\n|\r\n)", $line);
      foreach ($lines as $row) : 
        fwrite($tmpfile, "$row\n");
      endforeach; 
    }
    fclose($tmpfile);
    fclose($handle);
  endif;

  if (($handle = fopen("$filename.tmp", 'r')) !== FALSE) : 
    while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
      if (!@$row[0]) continue; if (!$header) : 
        $header = $row;
      else :
        $data[] = array_combine($header, $row);
      endif;
    }
    fclose($handle);
  endif;

  unlink("$filename.tmp");
  return $data;
}

1 comment:

  1. Get excellence difference between SSL and TLS, Their have proper explain of web security and insecurity that a bis reason of the excellence of this article.
    Germany VPS Server Hosting

    ReplyDelete