Clean DB Field Data for Excel Export

Description: Useful little function which cleans up database field data and prepares it for an Excel exporting. Can be used when generating CSV files of database table data.
Tested Platform: PHP 7+
Language: PHP
// Clean up data for Excel (CSV) exporting
// Expects: Field data to clean as a string
// Returns: Nothing, original string is cleaned in place.

function cleanData(&$str) { 
     $str = preg_replace("/t/", "\t", $str); 	
     $str = preg_replace("/r?n/", "\n", $str); 
        
     if (strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; 
} 

Posted: March 18, 2023

Return to the snippets listing