3

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!

4
  • You may not have permission to read the file. I copied and pasted your code and it works fine. If you're on a unix system you can do sudo chmod 744 values.txt Commented Jun 14, 2016 at 16:45
  • Get rid of @ fopen, so that you can see error if any. Use only fopen() Commented Jun 14, 2016 at 16:48
  • @ksealey I'm running on Windows 7. Later on in the program, I have javascript code that reads a .csv file just fine, so I don't think it could be a permissions issue. Thanks for the suggestion, though. Commented Jun 14, 2016 at 16:52
  • @Rohit I got rid of the @, but did not notice any errors. Commented Jun 14, 2016 at 16:53

1 Answer 1

2

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>';
Sign up to request clarification or add additional context in comments.

6 Comments

I tried your code just now, but still, the dropdown menu wasn't populated with anything... :(
@CdSdw give the full path to the file name.
The curly brackets syntax won't work with single quotes.
@Midas Thanks a lot and sorry to CdSdw for single quotes
Hmm I think it might be my newbie-ness at HTML, but when I create a new HTML file with <!DOCTYPE html><html lang="en"><body>(your code)</body></html>, the only thing displayed on the screen when I open the HTML file is the literal text "; foreach($eachlines as $lines){ echo "{$lines}"; } echo ""; ?>...I'm not sure why the echoes are being displayed literally. I changed all of the single quotes to double quotes to be safe.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.