Creating a select dropdown from a .txt?

2019-09-09 20:15发布

问题:

I've a select menu hardcoded in a wordpress (php) theme, but the manager requires to edit those frequently. Is it possible to populate the select dropdown options from a text file import? So he just has to edit the text file and the menu options would change.

The current menu looks like this:

<select name="location" id="sort-location" class="sort-dropdown"> 
            <option value="" selected="selected">LOCATION:</option> 
            <option value="" disabled="">--------------</option> 
            <option value="hongkong">Hong Kong</option> 
            <option value="taiwan">Taiwan</option> 
            <option value="mainland_china">Mainland China</option> 
            <option value="" disabled="">--------------</option> 
            <option value="">SHOW ALL</option> 
        </select>

回答1:

Sure -- make yourself a small loop that runs through the lines in the format you choose.

<?php
$select = file_get_contents('select.txt');
$lines = explode("\n", $select);
foreach ($lines as $line) {
    // let's say our format is like this:
    // value|name|selected|disabled
    // or:
    // -
    // for separator
    if ($line == '-') {
        echo '<option disabled="disabled">----------</option>';
    } else {
        list($value, $name, $selected, $disabled) = explode("|",$line);
        echo '<option value="'.$value.'"',
        $selected?' selected="selected"':'',
        $disabled?' disabled="disabled"':'',
        '>'.$name.'</option>';
    }
}
?>


回答2:

Sure, just fetch the text file into an array using file() and create the select out of it. A very simple implementation: menu.txt:

hongkong        Hong Kong   
taiwan          Taiwan
mainland_china  Mainland China

Note the tabs between value and label.

Then in PHP:

$menu_items = file("menu.txt");

foreach ($menu_items as $menu_item)
 {
   // Explode 
   $menu_item_exploded = explode("\t", $menu_item);
   $option_value = htmlspecialchars(trim($menu_item_exploded[0]));
   $option_label = htmlspecialchars(trim($menu_item_exploded[1]));

   echo "<option value='$option_value'>$option_label</option>";

 }

As far as I can see, you have the following left to solve:

  • How to pre-set a predefined value (You need to echo selected in the right item)

  • How to deal with the user editing out a value from the text file that was pre-set in your select.

  • Error handling if the file is not existent or not accessible

  • Error handling if the user screws up the line breaks, or something similar - maybe count the lines, and/or detect whether there are tabs inside the file