Looping through a csv with fgetcsv

怎甘沉沦 提交于 2020-02-21 10:44:05

问题


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

<?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).

Thanks.


回答1:


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

http://php.net/manual/en/function.fgetcsv.php

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.




回答2:


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

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

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



回答3:


Instead of print_r you may try echo

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

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

fclose($file);
?>


来源:https://stackoverflow.com/questions/26864675/looping-through-a-csv-with-fgetcsv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!