Convert arrays to CSV with PHP
•
1 min read
Heads up! This post was written in 2007, so it may contain information that is no longer accurate. I keep posts like this around for historical purposes and to prevent link rot, so please keep this in mind as you're reading.
— Cory
The following snippet will convert a simple PHP array into CSV (comma-separated values) format.
function csv($array) {
$csv = "";
for ($i = 0; $i < count($array); $i++) {
$csv .= '"' . str_replace('"', '""', $array[$i]) . '"';
if ($i < count($array) - 1) $csv .= ",";
}
return $csv;
}
Output #
$a = array("item 1", "item 2", "item 3");
echo csv($a); // "item 1","item 2","item 3"