Snippet. PHP. Array to CSV

Comma Separated Values (CSV) files are largely used throughout the IT industry to store, transfer or backup data because of its lean, yet perfectly readable structure. The functions bellow show how to convert a PHP array to CSV format.

function array_to_csv($array) {
    ob_start();
    $fp = fopen('php://output', 'w');
    foreach ($array as $row) {
        fputcsv($fp, $row);
    }
    fclose($fp);
    return ob_get_clean();
}

Updated on: 18 Apr 2024