Search code examples
phpfgetcsv

fgetcsv array print failing


!! Revised !! For some reason it's only printing one line of the csv, and double printing the country? csv preview output

<?php
$file = fopen('storelistdata.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
list($country[], $state[], $city[], $loc[]) = $line;
$arrayLength = count($line);
$i = 0;
while ($i < $arrayLength) {
echo "<a class=\"item\">" . $loc[$i] .",". $city[$i] .",". $state[$i] .",".$country[$i] . "<a/></br>";
$i++;
}
}
fclose($file);
?>

Solution

  • EDIT:

    CSV file

    United States,Alabama,Alburn,Earth Fare
    United States,Alabama,Huntsville,Earth Fare
    United States,Alabama,Montgomery,Earth Fare
    United States,Alabama,Hoover,Earth Fare
    United States,Alabama,Fairhope,Fairhope Health Foods
    

    Code:

    <?php
    $file = fopen('storelistdata.csv', 'r');
    while (($line = fgetcsv($file)) !== FALSE) {
     // Extract line array into these variables
     list($country, $state, $city, $loc) = $line;
     echo "<a class=\"item\">$loc, $city, $state, $country</a>\n";
    }
    fclose($file);
    ?>
    

    Result:

    <a class="item">Earth Fare, Alburn, Alabama, United States</a>
    <a class="item">Earth Fare, Huntsville, Alabama, United States</a>
    <a class="item">Earth Fare, Montgomery, Alabama, United States</a>
    <a class="item">Earth Fare, Hoover, Alabama, United States</a>
    <a class="item">Fairhope Health Foods, Fairhope, Alabama, United States</a>