A class used to read CSV files


/**
 * CsvProcessor.
 * 
 * @author Dribbit info@dribbit.eu
 *
 */
class CsvProcessor {

  /**
   * Process csv files and return as an associated or indexed array
   * depending if headers are set.
   * 
   * @param $file
   *  String File path.
   * @param $length
   * Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). 
   * By setting to 0, the maximum line length is not limited, which is slightly slower. 
   * @param $delimeter
   *  String containing the CSV delimeter.
   * @param $headers
   *  Boolean
   *  
   * @return array
   * 
   */
  public static function Process ($file, $delimeter = ';', $length = 1000, $headers = true) {
    
    $setHeader = true;
    $rows = array();
    $handle = fopen($file, 'r');
    
    if (!$handle)
      exit('Unable to open file');
  
    while ((($data = fgetcsv($handle, $length, $delimeter)) !== FALSE)) {
      if ($headers) {
        if ($setHeader === true) {
          $headingTexts = $data;
          $setHeader = false;
        } else {
          foreach ($data as $key => $value) {
            unset($data[$key]);
            $data[$headingTexts[$key]] = $value;
          }
          $rows[] = $data;
        }
      } else {
        foreach ($data as $key => $value) {
          $data[$key] = $value;
        }
        $rows[] = $data;
      }
    }
    fclose($handle);
    
    return $rows;
  }
  
}

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.