Question

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
)
Was it helpful?

Solution

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.

OTHER TIPS

Try this:-

ini_set('auto_detect_line_endings', TRUE);/// (PHP's detection of line endings) write at the top.


$csvrows = array_map('str_getcsv', file($filepath));
$csvheader = array_shift($csvrows);
$csv = array();
foreach ($csvrows as $row) {
   $csv[] = array_combine($csvheader, $row);
}

try-

$csv = array();

if (($file = fopen('test.csv', 'r')) === false) {
    throw new Exception('There was an error loading the CSV file.');
} else {  
   while (($line = fgetcsv($file, 1000)) !== false) {
      $csv[] = $line;
   }
   fclose($handle);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top