Populate HTML dropdown from text file

I have a dropdown menu with hard-coded values:

<select name="value" id="value">
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
  <option value="D">D</option>
</select>

I would like to load a text file to populate the values. The text file will have each value on a new line.

values.txt

A
B
C
D

I’ve tried this:

<select>
    <?php
    if ($file = @fopen('values.txt', 'r')) {
        while(($line = fgets($file)) !== false) {
            echo "<option>{$line}</option>";
        }
        fclose($file);
    }
?>
</select>

But there are no choices on the dropdown when I do this.

Any help would be appreciated. Thanks!

Answer

You can create an array element of the list

$filename = 'values.txt';
$eachlines = file($filename, FILE_IGNORE_NEW_LINES);//create an array
echo '<select name="value" id="value">';
foreach($eachlines as $lines){
    echo "<option>{$lines}</option>";
}
echo '</select>';

Leave a Reply

Your email address will not be published. Required fields are marked *