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 5
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) . '"'; 

Submitted: December 24, 2012

Return to the snippets listing