0

I'm trying to parse a CSV file in PHP and work with the values, however my code is only returning data from the first line of the CSV file.

The CSV file looks like this

C,  QXM0039326, ,           X6, 2288314208
C,  QXP0039226, 7021130,    X6,     100013427

The php looks like this:

if (($handle = fopen("easy.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",", "\n")) !== FALSE) 
    {
        // do something with the data here
        echo $data[0] . " - ". $data[1] . " - ". $data[2] . "</br>" ;
    }

    fclose($handle);
}

This produces the expected results for $data[0] etc, but only the 1st line of the csv. So I get an output result like this:

C - QTM0039326 - 2288314208

This is exactly the output that I want, however for every line in the CSV.

I've tried to iterate over the $data like so

if (($handle = fopen("easy.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",", "\n")) !== FALSE) 
    {
        // do something with the data here
        foreach ($data as $row){
            echo $row[0] . " - ". $row[1] . " - ". $row[4] . "</br>" ;
    }   
    fclose($handle);
}

}

But this gives me a really whack result like this (continuing on):

C - - 
Q - T - 0
- - 
X - 6 - 
2 - 2 - 3

What do I have to do to get the results I'm after (i.e. C - QTM0039326 - 2288314208 ) but for every line of the CSV?

0

2 Answers 2

2

Youve closed the file handle inside your loop, so there isnt anything on the next iteration....

Should look like:

if (($handle = fopen("easy.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",", "\n")) !== FALSE) 
    {
        // do something with the data here
        echo $data[0] . " - ". $data[1] . " - ". $data[2] . "</br>" ;
    }

    fclose($handle);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This still only returns the first result. I've edited the question to take the close out of the loop.
1

Try changing this one line. May be there is problem with the line break.

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 

1 Comment

Although this wasn't the correct answer, it led me to the answer. There was a problem in the CSV and the line break wasn't being recognised. I added a ";" at the end of every line and changed to while (($data = fgetcsv($handle, 1000, "," ";")) !== FALSE) which worked. Auto detect as in your answer also worked - so now I have to look at the CSV and why it's giving a whack line break. Thanks!

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.