4 * @version V4.93 10 Oct 2006 (c) 2000-2011 John Lim (jlim#natsoft.com). All rights reserved.
5 * Released under both BSD license and Lesser GPL library license.
6 * Whenever there is any discrepancy between the two licenses,
7 * the BSD license will take precedence.
9 * Code to export recordsets in several formats:
12 * $s = rs2csv($rs); # comma-separated values
13 * $s = rs2tab($rs); # tab delimited
16 * $f = fopen($path,'w');
24 // returns a recordset as a csv string
25 function rs2csv(&$rs,$addtitles=true)
27 return _adodb_export($rs,',',',',false,$addtitles);
30 // writes recordset to csv file
31 function rs2csvfile(&$rs,$fp,$addtitles=true)
33 _adodb_export($rs,',',',',$fp,$addtitles);
36 // write recordset as csv string to stdout
37 function rs2csvout(&$rs,$addtitles=true)
39 $fp = fopen('php://stdout','wb');
40 _adodb_export($rs,',',',',true,$addtitles);
44 function rs2tab(&$rs,$addtitles=true)
46 return _adodb_export($rs,"\t",',',false,$addtitles);
50 function rs2tabfile(&$rs,$fp,$addtitles=true)
52 _adodb_export($rs,"\t",',',$fp,$addtitles);
56 function rs2tabout(&$rs,$addtitles=true)
58 $fp = fopen('php://stdout','wb');
59 _adodb_export($rs,"\t",' ',true,$addtitles);
63 function _adodb_export(&$rs,$sep,$sepreplace,$fp=false,$addtitles=true,$quote = '"',$escquote = '"',$replaceNewLine = ' ')
70 $escquotequote = $escquote.$quote;
74 $fieldTypes = $rs->FieldTypesArray();
77 while(list(,$o) = each($fieldTypes)) {
79 $v = ($o) ?
$o->name
: 'Field'.($i++
);
80 if ($escquote) $v = str_replace($quote,$escquotequote,$v);
81 $v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))));
85 $s .= implode($sep, $elements).$NEWLINE;
87 $hasNumIndex = isset($rs->fields
[0]);
90 $max = $rs->FieldCount();
97 for ($j=0; $j < $max; $j++
) {
99 if (!is_object($v)) $v = trim($v);
101 if ($escquote) $v = str_replace($quote,$escquotequote,$v);
102 $v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))));
104 if (strpos($v,$sep) !== false ||
strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";
105 else $elements[] = $v;
107 } else { // ASSOCIATIVE ARRAY
108 foreach($rs->fields
as $v) {
109 if ($escquote) $v = str_replace($quote,$escquotequote,trim($v));
110 $v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v))));
112 if (strpos($v,$sep) !== false ||
strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";
113 else $elements[] = $v;
116 $s .= implode($sep, $elements).$NEWLINE;
119 if ($fp && ($line %
$BUFLINES) == 0) {
120 if ($fp === true) echo $s;
127 if ($fp === true) echo $s;