10

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
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Andres SK
  • 10,779
  • 25
  • 90
  • 152
  • 2
    Are you sure those are `"` chars and not the fancy 66's and 99's that MS loves to sprinkle everywhere? – Marc B Sep 21 '11 at 15:27
  • Works fine for me. Probably a bug in your `PHP_VERSION`. (Which is it?) Alternatively try `var_dump(array_map("str_getcsv", file($fn)))`. – mario Sep 21 '11 at 15:28
  • @StefanPantke: Now that you mention it. He gets exactly one record out of it. So it's the line breaks which are not recognized, therefore the quotes being misinterpreted as well. – mario Sep 21 '11 at 15:34
  • See also php.ini setting `auto_detect_line_endings` – mario Sep 21 '11 at 17:13
  • @StefanPantke: The `1` is just the result of `print_r()` which gets written out by the `echo` *after* print_r itself already threw its output out. (Why it's also not within the pre tags.) – mario Sep 21 '11 at 17:34
  • @MarcB yes, the " are normal quotes – Andres SK Sep 21 '11 at 19:36
  • @StefanPantke i fixed the output, still that is not the issue. I think Mario kind of has a point with the line breaks though. – Andres SK Sep 21 '11 at 19:38
  • Possible duplicate of [How to create an array from a CSV file using PHP and the fgetcsv function](https://stackoverflow.com/questions/1269562/how-to-create-an-array-from-a-csv-file-using-php-and-the-fgetcsv-function) – Ali Hesari Sep 21 '17 at 19:11

4 Answers4

20

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.

mario
  • 144,265
  • 20
  • 237
  • 291
3

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);
}
vineet
  • 13,832
  • 10
  • 56
  • 76
1

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);
}
Don
  • 3,987
  • 15
  • 32
Rekha
  • 41
  • 5
0

To fix this, you can try trimming the whitespace from each line before parsing it with fgetcsv.

if (($handle = fopen('test.csv', 'r')) !== FALSE) {
    while (($line = fgets($handle)) !== FALSE) {
        $line = trim($line); // Trim whitespace from the line
        $data = str_getcsv($line, ',', '"'); // Parse CSV data
        
        echo '<pre>';
        print_r($data);
        echo '</pre>';
    }
    fclose($handle);
}

In updated code, we use fgets to read each line of the file and then trim to remove any leading or trailing whitespace. Finally, str_getcsv is used to parse the CSV data.

tec
  • 5
  • 6
  • 1
    What makes you think that `fgets()` is suffering from whitespace characters at the start or end of the line? I am doubtful that this advice will resolve the asker's problem with newline characters in the file. The asker's `$data` (your `$line`) seems to parsing the csv file as though there are no newlines in it at all. – mickmackusa May 31 '23 at 06:18