Remark: The .txt document mentioned in the question contains the list of world countries. It is a list with fixed content; it doesn't change during the execution of the program, it doesn't change between different executions of the program. It changes sometimes, not very often, when an entry is added or removed from the list. More often, the code or the name of existing items change.
This answer is tailored to the content of the file. It is not a recipe good for all situations.
The best way (given the content of the file you want to load) is to have the list of country names indexed by country code in the PHP code, in a separate file.
Something like this (file listCountries.php
):
<?php
// ISO-3166 country codes
return array(
'AF' => 'Afghanistan',
'AX' => 'Åland Islands',
'AL' => 'Albania',
// ...
);
// This is the end of file; there is no need for a PHP close tag
When you need to use it, all you have to do is to write something like this:
$listCountries = include 'listCountries.php`;
Of course, you should put it somewhere in a directory of included files and take care of the path in the include
line.
You can then iterate over $listCountries
and generate the HTML code you need:
<select>
<?php
// Assuming the country with code $selectedCode have to be already selected in the list
foreach ($listCountries as $code => $name) {
$selected = ($code == $selectedCode) ? ' selected="selected"' : '';
echo('<option value="'.$code.'"'.$selected.'>'.htmlspecialchars($name)."</option>\n");
}
?>
</select>
You can generate the file using search and replace in your editor (if it knows search and replace with regular expressions) or you can write a little PHP script to generate the list for you:
$listCountries = array();
$fh = fopen('http://www.textfixer.com/resources/dropdowns/country-list-iso-codes.txt', 'r');
while (! feof($fh)) {
list($code, $name) = fgetcsv($fh, 0, ':');
$listCountries[$code] = $name;
}
fclose($fh);
echo("<?php\n");
echo('$listCountries = ');
var_export($listCountries);
echo(";\n");
echo("// That's all, folks!\n");
Run it using the PHP command line and it will dump the PHP code of the list to the output. You can either redirect its output to a file or change it to write the code into a file (the first option is easier).
You can read more about the ISO-3166 country codes on Wikipedia or you can get the up to date information directly from the authoritative source: the ISO.