X-Git-Url: https://jasonwoof.com/gitweb/?a=blobdiff_plain;f=csv.php;h=fd67a4338fc62c28fa4606595ba477d6051b7d87;hb=6175bd3f9882b714c80c0d71cc4bd9a269d5a641;hp=d2d90e33f23f31a84210858f3f159d9c709acf8a;hpb=18971ff5f0c4a74eac4b65c0c9a7b1b8a5be9b3f;p=wfpl.git diff --git a/csv.php b/csv.php index d2d90e3..fd67a43 100644 --- a/csv.php +++ b/csv.php @@ -4,14 +4,40 @@ # little sense, and does not actually have anything to do with commas. # pass in a 2d array (array of rows) and it'll send it to the browser +# I can't figure out how to get multi-line fields to work, so this replaces newlines with 4 spaces. function array2d_to_csv_download($data, $filename) { header('Content-type: application/csv'); header('Content-Disposition: attachment; filename=' . $filename); foreach($data as $row) { + $first = true; foreach($row as $el) { - echo '"' . str_replace('"', '""', $el) . "\"\t"; + if($first) { + $first = false; + } else { + echo "\t"; + } + echo '"' . str_replace("\n", " ", str_replace('"', '""', $el)) . '"'; } - echo "\n"; # apparently can be \n or \r\n + echo "\r\n"; } exit(); } + +# pass an array of associative arrays. keys from the first one will be used +# see arary2d_to_csv_download above for more details +function assocs_to_csv_download($data, $filename) { + if(count($data) < 1) { + $flats = array(); + } else { + $flats = array(array_keys($data[0])); + $keys =& $flats[0]; + foreach($data as $row) { + $flat = array(); + foreach($keys as $k) { + $flat[] = $row[$k]; + } + $flats[] = $flat; + } + } + array2d_to_csv_download($flats, $filename); +}