Convert Array Elements To CSV Format

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

The following code will convert a PHP array into CSV format.

Code

// Converts array elements to a CSV string
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); // Output: "item 1","item 2","item 3"
If you enjoyed this article, please share it with a friend!

One Response to Convert Array Elements To CSV Format

  1. Geo says:

    Two shortcuts you’re missing:

    you can use foreach($array as $i => $element)

    and you can use implode() to stick the commas in.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>