Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a csv with fgetcsv

Tags:

php

csv

fgetcsv

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.

like image 853
user3725781 Avatar asked Nov 11 '14 12:11

user3725781


People also ask

How do I iterate through a column in a CSV file in Python?

csv' in read mode and create a file object. Create a reader object (iterator) by passing file object in csv. reader() function. Now once we have this reader object, which is an iterator, then use this iterator with for loop to read individual rows of the csv as list of values.

Is it possible to add image in csv file?

The fastest way to import images with CSV product import is to use web upload from public websites or file-sharing services like Dropbox, Google Drive and others. Alternatively, you can upload images directly from the local drive and link them to the product image field in CSV.

What does Fgetcsv do in PHP?

The fgetcsv() function parses a line from an open file, checking for CSV fields.


1 Answers

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

$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.

like image 157
Cody Caughlan Avatar answered Oct 20 '22 00:10

Cody Caughlan