Converting CSV to array

Andres SK picture Andres SK · Sep 21, 2011 · Viewed 19.2k times · Source

I have this array with airport codes and city names (around 3500 lines).

code,city
"Abilene, TX ",ABI
"Adak Island, AK ",ADK
"Akiachak, AK ",KKI
"Akiak, AK ",AKI
"Akron/Canton, OH ",CAK
"Akuton, AK ",KQA
"Alakanuk, AK ",AUK
"Alamogordo, NM ",ALM

I need to convert that file into a php array. This is my code so far:

if(($handle = fopen('test.csv', 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ',', '"')) !== FALSE) {
        echo '<pre>';
            print_r($data);
            echo '</pre>';
    }
    fclose($handle);
}

Although I'm setting the delimiter and enclousure characters for the fgetcsv function, im getting this as a result:

Array
(
    [0] => code
    [1] => city
"Abilene
    [2] => TX "
    [3] => ABI
"Adak Island
    [4] => AK "
    [5] => ADK
"Akiachak
    [6] => AK "
    [7] => KKI
"Akiak
    [8] => AK "
    [9] => AKI
"Akron/Canton
    [10] => OH "
    [11] => CAK
"Akuton
    [12] => AK "
    [13] => KQA
"Alakanuk
    [14] => AK "
    [15] => AUK
"Alamogordo
    [16] => NM "
    [17] => ALM
)

Answer

mario picture mario · Sep 21, 2011

If it's the linebreaks, you can try the brute-force method with:

$file = file_get_contents("test.csv");
$data = array_map("str_getcsv", preg_split('/\r*\n+|\r+/', $file));
print_r($data);

str_getcsv is available with PHP 5.3, or as workaround in the manual, via upgradephp or PHP_Compat.