JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
clean up my urls
[wfpl.git] / csv.php
1 <?php
2
3 # These functions redutrn a csv download which is hopefully easy to import into
4 # Excell and LibreOffice Calc
5
6 # pass in a 2d array (array of rows) and it'll send it to the browser
7 # I can't figure out how to get multi-line fields to work, so this replaces newlines with 4 spaces.
8 function array2d_to_csv_download($data, $filename) {
9         header('Content-type: application/csv'); 
10         header('Content-Disposition: attachment; filename=' . $filename); 
11         foreach($data as $row) {
12                 $first = true;
13                 foreach($row as $el) {
14                         if($first) {
15                                 $first = false;
16                         } else {
17                                 echo ",";
18                         }
19                         echo '"' . str_replace("\n", "    ", str_replace('"', '""', $el)) . '"';
20                 }
21                 echo "\r\n";
22         }
23         exit();
24 }
25
26 # pass an array of associative arrays. keys from the first one will be used
27 # see arary2d_to_csv_download above for more details
28 function assocs_to_csv_download($data, $filename) {
29         if(count($data) < 1) {
30                 $flats = array();
31         } else {
32                 $flats = array(array_keys($data[0]));
33                 $keys =& $flats[0];
34                 foreach($data as $row) {
35                         $flat = array();
36                         foreach($keys as $k) {
37                                 $flat[] = $row[$k];
38                         }
39                         $flats[] = $flat;
40                 }
41         }
42         array2d_to_csv_download($flats, $filename);
43 }