Formatting CSV
"CSV" stands for "Comma-Separated Values". CSV is a popular plain text format often used especially for exporting and importing data to and from various spreadsheet software.
This article is for PHP programmers. I'll show you how to format CSV with PHP.
Do it with a function. Here is one that will do the trick.
function MakeCSVline($array) { $formattedarray = array(); foreach( $array as $chunk ) { if( preg_match('/[\"\'\r\n\,]/',$chunk) ) { $s = str_replace('"','""',$chunk); $formattedarray[] = '"' . $s . '"'; } else { $formattedarray[] = $chunk; } } return implode(',',$formattedarray); } # function MakeCSVline()
In a PHP script, call the function with an array of values. The function returns a line of CSV-formatted text.
Here is an example.
<?php $testarray = array( 'chocolate', 'Tom "Smiley" Thumb', 'The fortune, the freedom' ); $CSVline = MakeCSVline($testarray); echo $CSVline; function MakeCSVline($array) { $formattedarray = array(); foreach( $array as $chunk ) { if( preg_match('/[\"\'\r\n\,]/',$chunk) ) { $s = str_replace('"','""',$chunk); $formattedarray[] = '"' . $s . '"'; } else { $formattedarray[] = $chunk; } } return implode(',',$formattedarray); } # function MakeCSVline() ?>
The example script turns this array:
Array ( [0] => chocolate [1] => Tom "Smiley" Thumb [2] => The fortune, the freedom )
Into this CSV line:
chocolate,"Tom ""Smiley"" Thumb","The fortune, the freedom"
The MakeCSVline() function handles multi-line values as well as values that contain quotation marks or commas.
The CSV-creating function is a handy little tool for you PHP programmers.
(This content first appeared in Possibilities newsletter.)
Will Bontrager