Array PHP To CSV with Sanitizing arrays

Found this somewhere I forgot, what this do is when you have bunch of arrays but when a quotes or something else that will mess up the writing to csv, this is the best I could find so far.

function array_to_scv($array, $header_row = true, $col_sep = ",", $row_sep = "n", $qut = '"')
{
$output = '';
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;
}

Update found another good one


function convert_to_csv($input_array, $output_file_name, $delimiter)
{
/** open raw memory as file, no need for temp files */
$temp_memory = fopen('php://memory', 'w');
/** loop through array */
foreach ($input_array as $line) {
/** default php csv handler **/
fputcsv($temp_memory, $line, $delimiter);
}
/** rewrind the "file" with the csv lines **/
fseek($temp_memory, 0);
/** modify header to be downloadable csv file **/
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
/** Send file to browser for download */
fpassthru($temp_memory);
}

function convert()
{
/** Array to convert to csv */
$array_to_csv = Array(
Array(12566,
'Enmanuel',
'Corvo'
),
Array(56544,
'John',
'Doe'
),
Array(78550,
'Mark',
'Smith'
)
);
$this->convert_to_csv($array_to_csv, 'export.csv', ',');
}

Subscribe to You Live What You Learn

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe