Created
September 27, 2018 04:51
-
-
Save samjaninf/8db7a105c7d0d66c5031f5db48b5f3b3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Array to CSV Function | |
// Copyright (c) 2014-2016, Ink Plant | |
// https://inkplant.com/code/array-to-csv | |
// last updated May 10, 2016 | |
function array_to_csv($data,$args=false) { | |
if (!is_array($args)) { $args = array(); } | |
foreach (array('download','line_breaks','return','trim') as $key) { | |
if (array_key_exists($key,$args)) { $$key = $args[$key]; } else { $$key = false; } | |
} | |
//for this to work, no output should be sent to the screen before this function is called | |
if ($download) { | |
if ((is_string($download)) && (substr($download,-4) == '.csv')) { $filename = $download; } | |
else { $filename = 'download.csv'; } | |
header('Content-Type:text/csv'); | |
header('Content-Disposition:attachment; filename='.$filename); | |
} | |
if ($line_breaks == 'windows') { $lb = "\r\n"; } | |
else { $lb = "\n"; } | |
//get rid of headers row, if it exists (headers should exist as keys) | |
if (array_key_exists('headers',$data)) { unset($data['headers']); } | |
$csv = ''; | |
$i = 0; | |
foreach ($data as $row) { | |
$i++; | |
//display headers and save for later | |
if ($i == 1) { | |
$c = ''; | |
$headers = array(); | |
foreach ($row as $key => $value) { | |
$key = str_replace('"','""',$key); | |
if ($trim) { $key = trim($key); } | |
$csv .= $c.'"'.$key.'"'; $c = ','; | |
$headers[] = $key; | |
} | |
$csv .= $lb; | |
} | |
//display values | |
$c = ''; | |
foreach ($headers as $key) { | |
$value = $row[$key]; | |
$value = str_replace('"','""',$value); | |
if ($trim) { $value = trim($value); } | |
$csv .= $c.'"'.$value.'"'; $c = ','; | |
} | |
$csv .= $lb; | |
} | |
$csv = trim($csv); | |
if ($return) { return $csv; } | |
else { echo $csv; } | |
if ($download) { die(); } | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment