Tuesday 24 May 2016

Saving an array to CSV - Drupal 7 and other CMS's


After searching around for how to save an array as a CSV I made this method in one of my classes.

 I'm posting this a blog as it seemed a bit cleaner than many of the snippets and examples I'de seen.

 Check http://php.net/manual/en/function.fputcsv.php  for documentation if you need to write your own.

public function createCsv($list, $uri) {

  $file = fopen($uri, "w");

  foreach ($list as $line) {

    fputcsv($file, explode(',', $line));

  }

  fclose($file);

}


Pass this an array of a format like

$reportArray = [];

$reportArray[] = "Date, Offer, Count";

$reportArray[] = "01/01/1970, Free Sky, 1";

}


You can then call up with

  DailySummaryEmail::createCsv($csv_data_array, "public://folder/filename.csv");

No comments: