Source for file iam_csvdump.php

Documentation is available at iam_csvdump.php


1 <?php
2
3 /**
4 * IAM_CSVDump A class form performing a query dump and sending it to the browser or setting it or download.
5 * @package iam_csvdump
6 */
7
8 /**
9 * IAM_CSVDump A class form performing a query dump and sending it to the browser or setting it or download.
10 * @author Iván Ariel Melgrati <phpclasses@imelgrat.mailshell.com>
11 * @package iam_csvdump
12 * @version 1.0
13 *
14 * IAM_CSVDump A class form performing a query dump and sending it to the browser or setting it or download.
15 *
16 * Browser and OS detection for appropriate handling of download and EOL chars.
17 *
18 * Requires PHP v 4.0+ and MySQL 3.23+. Some portions taken from the CSV_UTIL_CLASS by Andrej Arn <andrej@blueshoes.org>.
19 *
20 * This library is free software; you can redistribute it and/or
21 * modify it under the terms of the GNU Lesser General Public
22 * License as published by the Free Software Foundation; either
23 * version 2 of the License, or (at your option) any later version.
24 *
25 * This library is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
28 * Lesser General Public License for more details.
29 */
30 class iam_csvdump
31 {
32
33 /**
34 * @desc Takes an array and creates a csv string from it.
35 *
36 * @access public
37 * @param Array $array (see below)
38 * @param String $separator Field separator ()default is ';')
39 * @param String $trim If the cells should be trimmed , default is 'both'. It can also be 'left', 'right' or 'both'. 'none' makes it faster since omits many function calls.
40 * @param Boolean $removeEmptyLines (default is TRUE. removes "lines" that have no value, would come out empty.)
41 * @return String A CSV String. It returns an empty string if there Array is empty (NULL)
42 * @todo Add param "fill to fit max length"?
43 */
44 function arrayToCsvString($array, $separator=';', $trim='both', $removeEmptyLines=TRUE) {
45 if (!is_array($array) || empty($array)) return '';
46
47 switch ($trim) {
48 case 'none':
49 $trimFunction = FALSE;
50 break;
51 case 'left':
52 $trimFunction = 'ltrim';
53 break;
54 case 'right':
55 $trimFunction = 'rtrim';
56 break;
57 default: //'both':
58 $trimFunction = 'trim';
59 break;
60 }
61 $ret = array();
62 reset($array);
63 if (is_array(current($array))) {
64 while (list(,$lineArr) = each($array)) {
65 if (!is_array($lineArr)) {
66 //Could issue a warning ...
67 $ret[] = array();
68 } else {
69 $subArr = array();
70 while (list(,$val) = each($lineArr)) {
71 $val = $this->_valToCsvHelper($val, $separator, $trimFunction);
72 $subArr[] = $val;
73 }
74 }
75 $ret[] = join($separator, $subArr);
76 }
77 return join("\n", $ret);
78 } else {
79 while (list(,$val) = each($array)) {
80 $val = $this->_valToCsvHelper($val, $separator, $trimFunction);
81 $ret[] = $val;
82 }
83 return join($separator, $ret);
84 }
85 }
86
87 /**
88 * @desc Works on a string to include in a csv string.
89 * @access private
90 * @param String $val
91 * @param String $separator
92 * @param Mixed $trimFunction If the cells should be trimmed , default is 'both'. It can also be 'left', 'right' or 'both'. 'none' makes it faster since omits many function calls.
93 * @return String
94 * @see arrayToCsvString()
95 */
96 function _valToCsvHelper($val, $separator, $trimFunction) {
97 if ($trimFunction) $val = $trimFunction($val);
98 //If there is a separator (;) or a quote (") or a linebreak in the string, we need to quote it.
99 $needQuote = FALSE;
100 do {
101 if (strpos($val, '"') !== FALSE) {
102 $val = str_replace('"', '""', $val);
103 $needQuote = TRUE;
104 break;
105 }
106 if (strpos($val, $separator) !== FALSE) {
107 $needQuote = TRUE;
108 break;
109 }
110 if ((strpos($val, "\n") !== FALSE) || (strpos($val, "\r") !== FALSE)) { // \r is for mac
111 $needQuote = TRUE;
112 break;
113 }
114 } while (FALSE);
115 if ($needQuote) {
116 $val = '"' . $val . '"';
117 }
118 return $val;
119 }
120
121 /**
122 * @desc Define EOL character according to target OS
123 * @access private
124 * @return String A String containing the End Of Line Sequence corresponding to the client's OS
125 */
126 function _define_newline()
127 {
128 $unewline = "\r\n";
129
130 if (strstr(strtolower($_SERVER["HTTP_USER_AGENT"]), 'win'))
131 {
132 $unewline = "\r\n";
133 }
134 else if (strstr(strtolower($_SERVER["HTTP_USER_AGENT"]), 'mac'))
135 {
136 $unewline = "\r";
137 }
138 else
139 {
140 $unewline = "\n";
141 }
142
143 return $unewline;
144 }
145
146 /**
147 * @desc Define the client's browser type
148 * @access private
149 * @return String A String containing the Browser's type or brand
150 */
151 function _get_browser_type()
152 {
153 $USER_BROWSER_AGENT="";
154
155 if (ereg('OPERA(/| )([0-9].[0-9]{1,2})', strtoupper($_SERVER["HTTP_USER_AGENT"]), $log_version))
156 {
157 $USER_BROWSER_AGENT='OPERA';
158 }
159 else if (ereg('MSIE ([0-9].[0-9]{1,2})',strtoupper($_SERVER["HTTP_USER_AGENT"]), $log_version))
160 {
161 $USER_BROWSER_AGENT='IE';
162 }
163 else if (ereg('OMNIWEB/([0-9].[0-9]{1,2})', strtoupper($_SERVER["HTTP_USER_AGENT"]), $log_version))
164 {
165 $USER_BROWSER_AGENT='OMNIWEB';
166 }
167 else if (ereg('MOZILLA/([0-9].[0-9]{1,2})', strtoupper($_SERVER["HTTP_USER_AGENT"]), $log_version))
168 {
169 $USER_BROWSER_AGENT='MOZILLA';
170 }
171 else if (ereg('KONQUEROR/([0-9].[0-9]{1,2})', strtoupper($_SERVER["HTTP_USER_AGENT"]), $log_version))
172 {
173 $USER_BROWSER_AGENT='KONQUEROR';
174 }
175 else
176 {
177 $USER_BROWSER_AGENT='OTHER';
178 }
179
180 return $USER_BROWSER_AGENT;
181 }
182
183 /**
184 * @desc Define MIME-TYPE according to target Browser
185 * @access private
186 * @return String A string containing the MIME-TYPE String corresponding to the client's browser
187 */
188 function _get_mime_type()
189 {
190 $USER_BROWSER_AGENT= $this->_get_browser_type();
191
192 $mime_type = ($USER_BROWSER_AGENT == 'IE' || $USER_BROWSER_AGENT == 'OPERA')
193 ? 'application/octetstream'
194 : 'application/octet-stream';
195 return $mime_type;
196 }
197
198 /**
199 * @desc Generates a CSV File from an SQL String (and outputs it to the browser)
200 * @access private
201 * @param String $dbname Name of the Database
202 * @param String $user User to Access the Database
203 * @param String $password Password to Access the Database
204 * @param String $host Name of the Host holding the DB
205 */
206 function _db_connect($dbname="mysql", $user="root", $password="", $host="localhost")
207 {
208 $result = @mysql_pconnect($host, $user, $password);
209 if(!$result) // If no connection, return 0
210 {
211 return false;
212 }
213
214 if(!@mysql_select_db($dbname)) // If db not set, return 0
215 {
216 return false;
217 }
218 return $result;
219 }
220
221 /**
222 * @desc Generates a CSV File from an SQL String (and outputs it to the browser)
223 * @access private
224 * @param String $query_string An SQL statement (usually a SELECT statement)
225 * @param String $dbname Name of the Database
226 * @param String $user User to Access the Database
227 * @param String $password Password to Access the Database
228 * @param String $host Name of the Host holding the DB
229 */
230 function _generate_csv($query_string, $dbname="mysql", $user="root", $password="", $host="localhost")
231 {
232 if(!$conn= $this->_db_connect($dbname, $user , $password, $host))
233 die("Error. Cannot connect to Database.");
234 else
235 {
236 $result = @mysql_query($query_string, $conn);
237 if(!$result)
238 die("Could not perform the Query: ".mysql_error());
239 else
240 {
241 $file = "";
242 $crlf = $this->_define_newline();
243 while ($str= @mysql_fetch_array($result, MYSQL_NUM))
244 {
245 $file .= $this->arrayToCsvString($str,",").$crlf;
246 }
247 echo $file;
248 }
249 }
250 }
251
252 /**
253 * @desc Generate the CSV File and send it to browser or download it as a file
254 * @access public
255 * @param String $query_string An SQL statement (usually a SELECT statement)
256 * @param String $filename Filename to use when downloading the File. Default="dump". If set to "", the dump is displayed on the browser.
257 * @param String $extension Extension to use when downloading the File. Default="csv"
258 * @param String $dbname Name of the Database to use
259 * @param String $user User to Access the Database
260 * @param String $password Password to Access the Database
261 * @param String $host Name of the Host holding the DB
262 */
263 function dump($query_string, $filename="dump", $ext="csv", $dbname="mysql", $user="root", $password="", $host="localhost" )
264 {
265 $now = gmdate('D, d M Y H:i:s') . ' GMT';
266 $USER_BROWSER_AGENT= $this->_get_browser_type();
267
268 if ($filename!="")
269 {
270 header('Content-Type: ' . $this->_get_mime_type());
271 header('Expires: ' . $now);
272 if ($USER_BROWSER_AGENT == 'IE')
273 {
274 header('Content-Disposition: inline; filename="' . $filename . '.' . $ext . '"');
275 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
276 header('Pragma: public');
277 }
278 else
279 {
280 header('Content-Disposition: attachment; filename="' . $filename . '.' . $ext . '"');
281 header('Pragma: no-cache');
282 }
283
284 $this->_generate_csv($query_string, $dbname, $user, $password, $host);
285 }
286 else
287 {
288 echo "<html><body><pre>";
289 echo htmlspecialchars($this->_generate_csv($query_string, $dbname, $user, $password, $host));
290 echo "</PRE></BODY></HTML>";
291 }
292 }
293 }
294 ?>

Documentation generated on Fri, 12 Dec 2003 18:43:03 -0300 by phpDocumentor 1.2.3