CsvController.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. class CsvController
  3. {
  4. public function csvExport() {
  5. $res = $this->db->Query($this->conf['export_query']);
  6. if ($this->db->Error($this->conf['export_query'])) return false;
  7. $firstRow = $res->fetch(PDO::FETCH_ASSOC);
  8. if (!$firstRow) return false;
  9. $columns = array_keys($firstRow);
  10. $this->columnDetails = array();
  11. for ($i = 0; $i < count($firstRow); $i++) {
  12. $$this->column_details[$columns[$i]] = $this->getColumnTypeFromQuery($res, $i);
  13. }
  14. $header = $this->db->getHeaderNames($columns);
  15. $fwh = fopen($this->conf['filename'], "w");
  16. fwrite($fwh, implode(';', $header)."\n");
  17. fwrite($fwh, implode(';', convertRow($firstRow))."\n");
  18. while($row = $res->fetch(PDO::FETCH_ASSOC)) {
  19. fwrite($fwh, implode(';', convertRow($row))."\n");
  20. }
  21. fclose($fwh);
  22. return true;
  23. }
  24. public function csvConvert($tableArray)
  25. {
  26. $result = "";
  27. foreach ($tableArray as $row)
  28. {
  29. $result .= implode(';', $this->convertRow($row)) . "\r\n";
  30. }
  31. return $result;
  32. }
  33. private function convertRow ($row) {
  34. $result = array();
  35. foreach ($row as $key => $value)
  36. {
  37. $result[] = $this->convertCell($value);
  38. }
  39. return $result;
  40. }
  41. private function convertCell ($cell, $format = "VAR_STRING") {
  42. switch ($format) {
  43. case 'VAR_STRING':
  44. return trim($cell);
  45. case 'FLOAT':
  46. case 'NEWDECIMAL':
  47. return number_format($cell, 2, ",", "");
  48. case 'DATE':
  49. return ($format == '0000-00-00') ? "" : $cell;
  50. default:
  51. return $cell;
  52. }
  53. return $cell;
  54. }
  55. }