1

I wrote this piece of code:

$handle = fopen('upload/EFT.csv', "r");  
   while (! feof($handle)) { 
    print_r(fgetcsv($handle));
    }
fclose($handle);

This is the file:

AKRV0002,AKR,V0002,Akron
AKRV0006,AKR,V0006,Akron
AKRV0007,AKR,V0007,Akron
AKRV0011,AKR,V0011,Akron
AKRV0012,AKR,V0012,Akron
ATLV0019,ATL,V0019,ATLANTA
ATLV0021,ATL,V0021,ATLANTA

It returns this:

Array ( [0] => AKRV0002 [1] => AKR [2] => V0002 [3] => Akron AKRV0006 [4] => AKR [5] => V0006 [6] => Akron AKRV0007 [7] => AKR [8] => V0007 [9] => Akron AKRV0011 [10] => AKR [11] => V0011 [12] => Akron AKRV0012 [13] => AKR [14] => V0012 [15] => Akron ATLV0019 [16] => ATL [17] => V0019 [18] => ATLANTA ATLV0021 [19] => ATL [20] => V0021 [21] => ATLANTA

How can I have this return each line in a new array?

0

2 Answers 2

4

See how array position 3 is "Akron AKRV0006" — that is the last value of line 1 and the first value of line 2. It appears that the newlines aren't being read correctly. Without your raw file, I can't tell why.

Once you have fixed that, you will see that fgetcsv reads only one line at a time (in other words, returns an array with the data from only one row), not all lines at once. So, you will need to loop and add each array to another array until fgetcsv returns no more data:

$data = array();
while ($row = fgetcsv($handle)) {
    $data[] = $row;
}
Sign up to request clarification or add additional context in comments.

2 Comments

The csv file was saved from within excel, is there a special way of saving it? Can you give me some pointers on this?
@MG1 You can try reading it as a raw string and outputting the raw ASCII code of each character, and seeing what characters fall between those values. Alternatively, you can type up a brand new file in your text editor and see if that gives you different results.
1

Do you happen to use an old Mac computer?

"Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem."

http://php.net/manual/en/function.fgetcsv.php

1 Comment

Nope, I'm using a brand new mac computer. I saved the file as csv from excel. Is there a special way of saving the file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.