Convert a PHP 2d-Array to CSV

Convert a 2-dimensional PHP array into a CSV string. This makes the php array into a convenient format for saving as a string.

$csv = "";

for ($i=0; $i<count($array); $i++) {
    $csv .= implode(",", $array[$i]) . PHP_EOL;
}

Example:

Given the PHP 2d array:

$array = array (
    array (Classic Collections,Abilene, TX 79602,2.71828​,red),
    array (Fabulous Finds,Abilene, TX 79601,3.14159​,blue),
    array (Honeycomb Tree,Abilene, TX 7960,1.41421​,green)
);

This PHP converts it to a CSV string:

$csv = "";
for ($i=0; $i<count($array); $i++) {
    $csv .= implode(",", $array[$i]) . PHP_EOL;
}

$csv contains the following text with return characters at the end of each line:

Classic Collections,Abilene, TX 79602",2.71828​,red
Fabulous Finds,Abilene, TX 79601",3.14159​,blue
Honeycomb Tree,Abilene, TX 79601",1.41421​,green

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use