PHP PHP Functions for CSV Parsing and Formatting

Learn how to parse and format CSV files in PHP using built-in functions like fgetcsv, fputcsv, and str_getcsv. Discover a new function, str_putcsv, for converting a multi-dimensional array to a CSV formatted string.

function str_putcsv($data) {
    $fh = fopen('php://temp', 'rw');
    fputcsv($fh, array_keys(current($data)));
    foreach ($data as $row) {
        fputcsv($fh, $row);
    }
    rewind($fh);
    $csv = stream_get_contents($fh);
    fclose($fh);
    return $csv;
}