简体   繁体   中英

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 (ie C - QTM0039326 - 2288314208 ) but for every line of the CSV?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM