PHP array to CSV
<?php
/**
* Reads a CSV file and generates an array whose key-names are the corresponding column-name from the CSV file
*
* @param string $file_path
* @param boolean $headers When set to true, will remove the array key at the [0] index which contains the
* column headers from the CSV. Currently using array_shift which removes the first
* array-key and also re-indexes the array.
* @return array
*/
function read_CSV($file_path, $headers = true)
{
$csv = array_map('str_getcsv', file($file_path));
array_walk($csv, function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
});
// remove the array key and data if data source contains column headers
if ($headers === true)
// remove the first array-key which contains the column headers, note that array_shift also re-indexes the array keys
array_shift($csv);
return $csv;
}
/**
* Writes to a CSV file and outputs the file once the function is called.
*
* Only accepts a 1-dimensional array
*
* @param [type] $filename [description]
* @param [type] $data [description]
* @return [type] [description]
*/
function write_CSV($filename = null, Array $columns, Array $data, $using_output_buffer = true)
{
/**
* Integrity checks
* (1) same amount of column names as there are array keys from data (not implemented)
* (2) placeholder text if no columns were provided
*/
if (empty($columns))
echo 'Column names not provided';
/**
* Determine if the output is to the output buffer or to a file directly
*/
if ($using_output_buffer === true) {
// define output buffer
header('Content-Description: File Transfer');
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename=' . $filename);
// open buffer
$output = fopen('php://output', 'w') or die ('Cannot open output buffer');
} else {
// write to file
$output = fopen($filename, 'w') or die ('Cannot open file');
}
// set column names
if (isset($columns))
fputcsv($output, $columns);
// write data array
foreach ($data as $subarray)
fputcsv($output, $subarray);
// release buffer
fclose($output) or die('Cannot close output buffer or file');
}