PHP Array to CSV
What is CSV?
CSV, Comma Separated Values, is a type of file. Spreadsheets software like Excel and databases such as MySQL ,among many others, can import and export CSV files thus CSV files can be used to transfer data in between a large variety of programs.
PHP Array to CSV Function
/**
* Generatting CSV formatted string from an array.
* By Sergey Gurevich.
*/
function array_to_scv($array, $header_row = true, $col_sep = ",", $row_sep = "\n", $qut = '"')
{
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;
}
PHP Array to CSV Function Input and Output
Input:
- Array - Subject array.
- Boolean - To display a header row of key values or not? (default value: true).
- String - Column separator (default value: ",").
- String - Row separator (default value: "\n" - newline).
- String - Quote character, used for quoting data and escaping (default value: ").
Output:
- Success - CSV formatted string.
- Failure - Boolean false.
PHP Array to CSV function Usage and Result
Script:
//Subject array.
$array[] = array('key1' => 'row1-1', 'key2' => 'row1-2', 'key3' => 'row1-3', 'key4' => 'row1-4', 'key5' => 'row1-5');
$array[] = array('key1' => 'row2-1', 'key2' => 'row2-2', 'key3' => 'row2-3', 'key4' => 'row2-4', 'key5' => 'row2-5');
$array[] = array('key1' => 'row3-1', 'key2' => 'row3-2', 'key3' => 'row3-3', 'key4' => 'row3-4', 'key5' => 'row3-5');
$array[] = array('key1' => 'row4-1', 'key2' => 'row4-2', 'key3' => 'row4-3', 'key4' => 'row4-4', 'key5' => 'row4-5');
echo '<pre>';
print_r($array);
echo '</hr>';
//Converting array to SCV.
$csv_data = array_to_scv($array, false);
print_r($csv_data);
echo '</pre>';
Result:
Array
(
[0] => Array
(
[key1] => row1-1
[key2] => row1-2
[key3] => row1-3
[key4] => row1-4
[key5] => row1-5
)
[1] => Array
(
[key1] => row2-1
[key2] => row2-2
[key3] => row2-3
[key4] => row2-4
[key5] => row2-5
)
[2] => Array
(
[key1] => row3-1
[key2] => row3-2
[key3] => row3-3
[key4] => row3-4
[key5] => row3-5
)
[3] => Array
(
[key1] => row4-1
[key2] => row4-2
[key3] => row4-3
[key4] => row4-4
[key5] => row4-5
)
)
"row1-1","row1-2","row1-3","row1-4","row1-5"
"row2-1","row2-2","row2-3","row2-4","row2-5"
"row3-1","row3-2","row3-3","row3-4","row3-5"
"row4-1","row4-2","row4-3","row4-4","row4-5"