简体   繁体   English

PHP解析CSV仅返回第一行

[英]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. 我正在尝试解析PHP中的CSV文件并使用这些值,但是我的代码仅从CSV文件的第一行返回数据。

The CSV file looks like this CSV文件如下所示

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

The php looks like this: php看起来像这样:

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. 这会产生$ data [0]等的预期结果,但只会产生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. 这正是我想要的输出,但是对于CSV中的每一行。

I've tried to iterate over the $data like so 我试图像这样遍历$ data

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? 对于CSV的每一行,我该怎么做才能得到所需的结果(即C-QTM0039326-2288314208)?

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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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