Udders
Udders

Reputation: 6976

CSV File build a select element

Is is possible to create a select menu in HTML from a CSV file? I have no idea how to go about this.

So I have a CSV that has two columns and multiple values, is there any way I can loop through the CSV file with PHP and output HTML, I have tried this so far.

$row = 1;
    if (($handle = fopen($_SERVER['DOCUMENT_ROOT']."/service/regions.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 133, ",")) !== FALSE) {
            $num = count($data);
            $row++;
            for ($c=0; $c < $num; $c++) {
                echo "<option value='".$data[$c]."'>".$data[$c]."</option>";
            }
        }
        fclose($handle);
    }

However this is giving the following output,

 <select>
    <option value='AB'>AB</option>
    <option value='Aberdeenshire'>Aberdeenshire</option>
    <option value='AG'>AG</option>
    <option value='Angus'>Angus</option>
    <option value='AM'>AM</option>
    <option value='Armagh'>Armagh</option>
 </select>

What I am wanting is to get the output like this,

<option value="AB">Aberdeenshire</option>

Where am i going wrong?

Upvotes: 0

Views: 1539

Answers (2)

Baba
Baba

Reputation: 95121

All you need is

$handle = fopen(__DIR__ . "/service/regions.csv", "r");
echo "<select>";
if ($handle !== FALSE) {
    $row = 0;
    while ( ($data = fgetcsv($handle, 133, ",")) !== FALSE ) {
        printf('<option value="%s">%s</option>', $data[0], $data[1]);
    }
    fclose($handle);
}
echo "</select>";

Output

<select>
    <option value="AB">Aberdeenshire</option>
    <option value="AG">Angus</option>
    <option value="AM">Armagh</option>
</select>

Upvotes: 1

james_tookey
james_tookey

Reputation: 905

$data[$c][0] will return the first column, $data[$c][1] will return the second column and so on. So just replace $data[$c] with the correct variable for your column.

Upvotes: 1

Related Questions