-
-
Save raihan-uddin/cade10682438774d1e8497c7c709e2c5 to your computer and use it in GitHub Desktop.
PHP : Array To CSV
This file contains 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
/** | |
* Generating CSV formatted string from an array. | |
*/ | |
function array_to_csv($array, $header_row = true, $col_sep = ",", $row_sep = "\n", $qut = '"') | |
{ | |
if (!is_array($array) or !is_array($array[0])) return false; | |
//Header row. | |
if ($header_row) | |
{ | |
foreach ($array[0] as $key => $val) | |
{ | |
//Escaping quotes. | |
$key = str_replace($qut, "$qut$qut", $key); | |
$output .= "$col_sep$qut$key$qut"; | |
} | |
$output = substr($output, 1)."\n"; | |
} | |
//Data rows. | |
foreach ($array as $key => $val) | |
{ | |
$tmp = ''; | |
foreach ($val as $cell_key => $cell_val) | |
{ | |
//Escaping quotes. | |
$cell_val = str_replace($qut, "$qut$qut", $cell_val); | |
$tmp .= "$col_sep$qut$cell_val$qut"; | |
} | |
$output .= substr($tmp, 1).$row_sep; | |
} | |
return $output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment