Skip to main content

Use PHP's native fgetcsv() and fputcsv() without file handles.

<?php

/**
 * Convert an Array into a CSV string
 *
 * Uses `fgetcsv()` with a string instead of a file handle.
 *
 * @param array $arr The Array to formatted as CSV.
 * @return string The formatted CSV string.
 */
function array_to_csv($arr)
{
    $outstream = fopen("php://temp", 'r+');
    fputcsv($outstream, $arr, ',', '"');
    rewind($outstream);
    $csv = fgets($outstream);
    fclose($outstream);
    return $csv;
}

/**
 * Convert a CSV String into an Array
 *
 * Uses `fputcsv` to convert an array to a string instead of writing
 * to a file handle.
 *
 * @param string $str The CSV formatted string.
 * @return array The CSV string as Array.
 */
function csv_to_array($str)
{
    $instream = fopen("php://temp", 'r+');
    fwrite($instream, $str);
    rewind($instream);
    $csv = fgetcsv($instream, 9999999, ',', '"');
    fclose($instream);
    return ($csv);
}

//
// example usage
//

$arr = array(
    'username' => 'jon',
    'password' => 'secret'
);

// array as csv string
$csvString = array_to_csv($arr);
echo $csvString;

// csv string as array
$csvArray = csv_to_array($csvString);
var_dump($csvArray);