AnchovyLegend
AnchovyLegend

Reputation: 12537

Converting CSV rows string into array

I am using an API that returns a CSV string as the following:

Date,Open,High,Low,Close,Volume,Adj Close 2014-06-13,3.10,3.30,3.10,3.30,6638300,3.30

I was wondering if there is an easy way to convert this CSV string to an associative array? I am familiar with working with a CSV file, but not sure what to do with a CSV file string response. I am trying to avoid writing the response to a file, just so I can read it back.

Note, writing this response to a CSV file would result in two rows and seven columns.

Upvotes: 0

Views: 769

Answers (2)

Nathan
Nathan

Reputation: 1700

As others have mentioned, str_getcsv() is your friend and is an easy method to convert a CSV string into an array. This function will return an array of results. If you'd like to make it an associative array, use array_combine().

Honestly, though -- str_getcsv() may be overkill. Consider this method using explode():

// so given this string returned by the API
$api_s = "Date,Open,High,Low,Close,Volume,Adj Close\r\n2014-06-13,3.10,3.30,3.10,3.30,6638300,3.30";

// split on carriage return & line feed into two strings
$api_r = explode("\r\n", $api_s);

// split keys and values by comma
$keys = explode(',', $api_r[0]);
$vals = explode(',', $api_r[1]);

// construct associative array
$my_assoc_r = array_combine($keys, $vals);

Upvotes: 0

user1978142
user1978142

Reputation: 7948

If the line terminator is \r\n, then first you need to explode them thru that. Then you can proces from there. Consider this example:

$data = explode("\r\n", $csv_string);
// get the headers first
$headers = array_map('trim', explode(',', array_shift($data)));
$new_data = array();
// get the values and use array combine to use the headers as keys for associative array
foreach($data as $values) {
    $pieces = explode(',', $values);
    // i just assigned it in an array, since we dont know how many lines of data you will receive
    $new_data[] = array_combine($headers, $pieces);
}

$new_data should yield something like this:

Array
(
    [0] => Array
        (
            [Date] => 2014-06-13
            [Open] => 3.10
            [High] => 3.30
            [Low] => 3.10
            [Close] => 3.30
            [Volume] => 6638300
            [Adj Close] => 3.30
        )

)

Or just the usual way of handling csv strings. Use str_getcsv().

$data = str_getcsv($csv_string, "\r\n");
$headers = explode(',', array_shift($data));
$data = array_combine($headers, explode(',',reset($data)));

Upvotes: 1

Related Questions