PHP array to csv

There is a library for CSV files which I have yet to use but seems promising: https://github.com/parsecsv/parsecsv-for-php/blob/master/parsecsv.lib.php


The following is a simple function which I have used in the past. I would recommend using the library instead though.

<?php
/**
 * Converts an array to a csv compatible string.
 * 
 * @return string A string formatted for csv or an empty string on failure.
 */
function array_to_csv($array, $header_row = true, $col_sep = ",", $row_sep = "\n", $qut = '"') {
  if (!is_array($array) || !is_array($array[0]))
    return '';
  // header row
  if ($header_row) {
    foreach ($array[0] as $key => $val) {
      //Escaping quotes.
      $key = str_replace($qut, "$qut$qut", $key);
      $output .= "$col_sep$qut$key$qut";
    }
    $output = substr($output, 1) . "\n";
  }
  //Data rows.
  foreach ($array as $key => $val) {
    $tmp = '';
    foreach ($val as $cell_key => $cell_val) {
      //Escaping quotes.
      $cell_val = str_replace($qut, "$qut$qut", $cell_val);
      $tmp .= "$col_sep$qut$cell_val$qut";
    }
    $output .= substr($tmp, 1) . $row_sep;
  }
 
  return $output;
}
?>

Tags

External References

Article Type

General