Created
December 12, 2012 11:26
-
-
Save vrushank-snippets/4267086 to your computer and use it in GitHub Desktop.
PHP : Array To CSV
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
/** | |
* 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