JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Fix db_get_value after mysql->mysqli upgrade
[wfpl.git] / csv.php
1 <?php
2
3 # This program is in the public domain within the United States. Additionally,
4 # we waive copyright and related rights in the work worldwide through the CC0
5 # 1.0 Universal public domain dedication, which can be found at
6 # http://creativecommons.org/publicdomain/zero/1.0/
7
8 # These functions redutrn a csv download which is hopefully easy to import into
9 # Excell and LibreOffice Calc
10
11 # pass in a 2d array (array of rows) and it'll send it to the browser
12 # I can't figure out how to get multi-line fields to work, so this replaces newlines with 4 spaces.
13 function array2d_to_csv_download($data, $filename) {
14         header('Content-type: application/csv'); 
15         header('Content-Disposition: attachment; filename=' . $filename); 
16         foreach($data as $row) {
17                 $first = true;
18                 foreach($row as $el) {
19                         if($first) {
20                                 $first = false;
21                         } else {
22                                 echo ",";
23                         }
24                         echo '"' . str_replace("\n", "    ", str_replace('"', '""', $el)) . '"';
25                 }
26                 echo "\r\n";
27         }
28         exit();
29 }
30
31 # pass an array of associative arrays. keys from the first one will be used
32 # see arary2d_to_csv_download above for more details
33 function assocs_to_csv_download($data, $filename) {
34         if(count($data) < 1) {
35                 $flats = array();
36         } else {
37                 $flats = array(array_keys($data[0]));
38                 $keys =& $flats[0];
39                 foreach($data as $row) {
40                         $flat = array();
41                         foreach($keys as $k) {
42                                 $flat[] = $row[$k];
43                         }
44                         $flats[] = $flat;
45                 }
46         }
47         array2d_to_csv_download($flats, $filename);
48 }