php 使用 fgetcsv 循环遍历 csv

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26864675/
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-25 23:05:13  来源:igfitidea点击:

Looping through a csv with fgetcsv

phpcsvfgetcsv

提问by user3725781

I have a csv file with 3 columns: email address, first nameand last name. I have got the stage where I can print out the array using the following code:

我有一个包含 3 列的 csv 文件:电子邮件地址名字姓氏。我已经到了可以使用以下代码打印出数组的阶段:

<?php
$file = fopen("testEmails.csv","r");

while(! feof($file))
{
print_r(fgetcsv($file));
}

fclose($file);
?>

This prints the array, so every field in a row. What I want it to print is purely the values in the first column of the row. How would this be done, documentation on fgetcsv seems very sketchy to me (a relative beginner).

这将打印数组,因此在一行中的每个字段。我希望它打印的纯粹是该行第一列中的值。这将如何完成,关于 fgetcsv 的文档对我来说似乎很粗略(一个相对的初学者)。

Thanks.

谢谢。

回答by Cody Caughlan

The first example in the fgetcsv()documentation contains the nuggets of what you need.

fgetcsv()文档中的第一个示例包含您需要的内容。

$file = fopen("testEmails.csv","r");

while (($data = fgetcsv($file)) !== FALSE)
{
    echo "email address " . $data[0];
}

fgetcsv()returns a numerically indexed array of representing the columns, so you just want to print the first column.

fgetcsv()返回表示列的数字索引数组,因此您只想打印第一列。

回答by mainstreetmark

You're quite close. You could just print the first column since you already have the array.

你很接近。您可以只打印第一列,因为您已经有了数组。

But, you could also use fgetcsvitself as the control variable for the loop.

但是,您也可以将fgetcsv其自身用作循环的控制变量。

while (($array = fgetcsv($file)) !== FALSE) {
      print_r($array[0]);
}

回答by Penny

Instead of print_ryou may try echo

而不是print_r你可以尝试echo

<?php
$file = fopen("testEmails.csv","r");

while(! feof($file))
{
echo fgets($file). "<br />";
}

fclose($file);
?>