Possible Duplicate:
How to create an array from a CSV file using PHP and the fgetcsv function
I have a file that contains multiple rows of comma delimited values. A sample of the file is:
1359739665,511251515,115151515,start,1277771750,,2215812581258,31.55.115.12,0,0
1359739665,511251515,115151515,restore,1277771750,,2215812581258,31.55.115.12,0,0
1359739665,511251515,115151515,restore,1277771750,,2215812581258,31.55.115.12,0,0
1359739665,511251515,115151515,end,1277771750,,2215812581258,31.55.115.12,0,0
I basically need to iterate through each row. At the moment, this is my code:
$file = "log.txt";
$contents = file_get_contents($file);
$fields = explode(',', $contents);
foreach ($fields as $row)
{
echo $row;
}
This works fine for outputting the entire file. But my question is how do I iterate one row at a time. Each row essentially ends without the comma but I’m not sure how to force a break there. What I’d like to do is this (even though code is incorrect):
foreach ($fields as $row) //need $row to equal each row of the log
{
echo $row[0]; // will output 1359739665
echo $row[1]; // will output 511251515
etc...
}
Thank you!
You should use either
str_getcsv()orfgetcsv()to read CSV data.An example using
fgetcsv():An example using
str_getcsv():Using
explode()to manually parse CSV data might cause problems when your CSV fields may contain commas within their values or when the file endings of the CSV file isn’t consistent. It is best to use the specialized functions described above as they are tailored for this specific task.