I'm using PHP to open and parse a very small (around 1kb) CSV file to generate an HTML table. I'm new to PHP and this is largely experimental. In addition to generating the HTML table, I'm trying to generate an array from a particular set of columns in that csv (city and country information), then remove duplicate values. The CSV is structured like this:
Last Name, First Name, City, Country, Language
Smith, Joe, Shanghai, China, English
Jackson, Stacey, Madrid, Spain, Spanish
Jones, Bob, London, United Kingdom, English
Seward, Elisa, Madrid, Spain, English
Harrison, Tim, Berlin, Germany, German
The idea here is that in addition to a table with all the data, I'll also have a list of all the cities/countries listed in the table:
- Shanghai, China
- Madrid, Spain
- London, United Kingdom
- Berlin, Germany
Thanks to the fgetcsv() documentation and other questions on Stack Overflow, reading the file and building the table is straightforward:
<?php
$handle = fopen("namelist.csv", "r");
$data = fgetcsv($handle, 1000, ",");
echo('<table>');
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo("<tr>\r\n");
foreach ($data as $index=>$val) {
echo("\t<td>");
echo htmlentities($val, ENT_QUOTES);
echo("</td>\r\n");
}
echo("</tr>\r\n");
}
echo("</table>");
fclose($handle);
?>
But I've been unable to figure out how to grab city, country data and remove duplicates. Does anyone have suggestions?
$index == 2you have City, and when$index == 3you have Country. To remove duplicates you'll need to refer to the data array or store the information in a more user friendly array to keep track of what's been written.