From 7d0576e1a0098c1a34ca2a2a89e140f598d5c5e5 Mon Sep 17 00:00:00 2001
From: Peter Rotich <peter@osticket.com>
Date: Wed, 23 Apr 2014 22:00:32 +0000
Subject: [PATCH] Add ability to pass output file to result set exporter

This is necessary in case the exporter wants to redirect output to a file.
Use built-in PHP functions to encode and output CSV content
---
 include/class.export.php | 21 ++++++++++++++-------
 1 file changed, 14 insertions(+), 7 deletions(-)

diff --git a/include/class.export.php b/include/class.export.php
index 862a21496..0cd672a02 100644
--- a/include/class.export.php
+++ b/include/class.export.php
@@ -152,12 +152,16 @@ class Export {
 }
 
 class ResultSetExporter {
+    var $output;
+
     function ResultSetExporter($sql, $headers, $options=array()) {
         $this->headers = array_values($headers);
         if ($s = strpos(strtoupper($sql), ' LIMIT '))
             $sql = substr($sql, 0, $s);
         # TODO: If $filter, add different LIMIT clause to query
         $this->options = $options;
+        $this->output = $options['output'] ?: fopen('php://output', 'w');
+
         $this->_res = db_query($sql);
         if ($row = db_fetch_array($this->_res)) {
             $query_fields = array_keys($row);
@@ -211,14 +215,17 @@ class ResultSetExporter {
 }
 
 class CsvResultsExporter extends ResultSetExporter {
+
     function dump() {
-        echo '"' . implode('","', $this->getHeaders()) . "\"\n";
-        while ($row=$this->next()) {
-            foreach ($row as &$val)
-                # Escape enclosed double-quotes
-                $val = str_replace('"','""',$val);
-            echo '"' . implode('","', $row) . "\"\n";
-        }
+
+        if (!$this->output)
+             $this->output = fopen('php://output', 'w');
+
+        fputcsv($this->output, $this->getHeaders());
+        while ($row=$this->next())
+            fputcsv($this->output, $row);
+
+        fclose($this->output);
     }
 }
 
-- 
GitLab