#native_company# #native_desc#
#native_cta#

CSV Export

By Leo
on August 21, 2003

Version: 1.0

Type: Function

Category: Other

License: GNU General Public License

Description: Export your data to a csv and read with Excel

<?php
/*
 *  Export your array to csv
 *  Created by Leo Watanabe <leow_74 at yahoo dot com> - August 2003
 */

// Caution: $data MUST be an array of array
function convertToExcelCSV($data) {
  // Sorry, not an array...
  if(!is_array($data)) { return ''; }
  $csv = '';
  foreach($data as $record) {
    // all record must be an array
    if(is_array($record)) {
      // convert this record to csv
      $csv .= convertArrayToCSV($record) . "rn";
    }
  }
  return $csv;
}

// convert an array to csv
function convertArrayToCSV($record) {
  // need to test because I don't have privative functions :(((
  if(!is_array($record)) { return ''; }
  $ret = '';
  foreach($record as $field) {
    if (is_array($field)) {
      // convert recusively
      $ret .= convertArrayToCSV($field);
    }
    else {
      // if field has double quotes or commas
      if (strpos($field,'"')!==false || strpos($field,',')!==false) {
        // replace " by "", and put all inside "
        // "all_field_value,_will_be_here"
        $ret .= '"' . str_replace('"','""',$field) . '"';
      }
      else {
        $ret .= $field;
      }
    }
    // comma separated values
    $ret .= ',';
  }
  // strip last comma
  return substr($ret, 0, strlen($ret)-1);
}

?>