James
James

Reputation: 3273

PHP parsing CSV only returning 1st line

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?

Upvotes: 0

Views: 192

Answers (2)

GBRocks
GBRocks

Reputation: 698

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

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

Upvotes: 1

prodigitalson
prodigitalson

Reputation: 60413

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);
}

Upvotes: 2

Related Questions