php PHP逐行读取CSV文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37361786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:11:57  来源:igfitidea点击:

PHP read CSV file line by lines

phpcsv

提问by chouaib23

I have a CSV file loaded from an URL, and I want to loop over the lines with PHP.

我有一个从 URL 加载的 CSV 文件,我想用 PHP 遍历这些行。

Here is a typical line of this CSV:

这是此 CSV 的典型行:

1004000018;active;"TEST1";"TEST2";"TEST3";"TEST4" 

I would like to get this result, for each row:

对于每一行,我想得到这个结果:

1004000018
active
TEST1
TEST2
TEST3
TEST4

回答by Sofiene Djebali

You can achieve this using the php function fgetcsv, this should work :

您可以使用 php 函数fgetcsv实现这一点,这应该可以工作:

PHP

PHP

$file = fopen('file.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
   //$line[0] = '1004000018' in first iteration
   print_r($line);
}
fclose($file);

回答by Surendra Suthar

This will help you for read csv:

这将帮助您读取 csv:

   if (($handle = fopen("$source_file", "r")) !== FALSE) {
        $columns = fgetcsv($handle, $max_line_length, $delemietr);
        if (!$columns) {
            $error['message'] = 'Empty';
             return ($error);
        }

        while (($rows = fgetcsv($handle, 10000, "\t")) !== false) {
            if ($rows[1] && array(null) !== $rows) { // ignore blank lines
                        $data1 = $rows[1];
              }
            }
    }