0

I'm not sure if this is the best way of doing this or if it is even possible however what I'm trying to achieve is to echo out all these countries as a list in a select dropdown here is the list Country text document

So my question is how would I display these in a select dropdown or if I can't do this the way I'm trying to do it what would be the best way of doing it without manually adding each country to the form?

<select>
  <option value="GB: United Kingdom">GB: United Kingdom</option>
  <option value="etc">etc</option>
  <option value="etc">etc</option>
  <option value="etc">etc</option>
</select>
Peanuts
  • 53
  • 6
  • You read the file line by line, so iterate over all linesThen all that is left to do in each iteration is to output a select option where you fill in the lines content as required. – arkascha Mar 08 '16 at 15:06
  • Have you tried anything? Post your code, please. – aslawin Mar 08 '16 at 15:07
  • Thankyou @arkascha and aslawin I wouldn't know where to begin in achieving this is it possible you can provide an example? I appreciate your comments though and It will be defiantly be easier for me to look this up online knowing where to begin – Peanuts Mar 08 '16 at 15:08
  • Try to follow answers for this question: http://stackoverflow.com/questions/13246597/how-to-read-a-file-line-by-line-in-php – alexander.polomodov Mar 08 '16 at 15:08
  • @alexander.polomodov Very useful thankyou. – Peanuts Mar 08 '16 at 15:11

3 Answers3

0

A simple example which certainly needs more love:

<?php
$fh = fopen('list.text', 'r');
?>

<select>
<?php
while ($line = fgets($fh, 1024)) {
    echo sprintf('  <option value="%1$s">%1$s</option>'."\n", trim($line));
}
?>
</select>

The output obviously is:

<select>
  <option value="AF:Afghanistan">AF:Afghanistan</option>
  <option value="AX:Åland Islands">AX:Åland Islands</option>
  .....
</select>
arkascha
  • 41,620
  • 7
  • 58
  • 90
0

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.

axiac
  • 68,258
  • 9
  • 99
  • 134
  • Thankyou very useful – Peanuts Mar 08 '16 at 15:45
  • I just added the code that uses `$listCountries` to generate the HTML – axiac Mar 08 '16 at 15:46
  • This is questionable, since it does not scale. Your approach requires to hold all data in memory and even multiplying it a few time. That means that with rising size of the list your memory consumption rises exponentially. Also this does not allow to swap the data resource in a dynamic manner. Not really an elegant solution in my eyes, though certainly working. – arkascha Mar 08 '16 at 17:33
  • @arkascha The list is fixed. There is nothing to scale on it. It is the list of world countries. It doesn't change every day. And when it changes, it maybe enlarges or shrinks with one item. More often the codes or the country names change. Memory consumption? `35616 bytes` using PHP 5.6. `12344 bytes` using PHP 7.0. Since the code doesn't change the list, PHP doesn't keep multiple copies of it in memory. Nothing prevents you to initialize `$listCountries` with something else (but it doesn't make much sense). – axiac Mar 08 '16 at 17:42
  • I don't know if the list changes or not. That is an assumption, not more, not less. – arkascha Mar 08 '16 at 17:46
-2

The short answer is yes it is possible, but is it the best way? No, it isn't, there are many other better ways than plain text storage.

If you ask for advice I would tell you to do it from a DB table or from a JSON, even from a XML.

If you are going to change your mind and use one of these methods I recommend you to google it (You can find the structure that suits your application).

Any way as a guidance I have used these two recently:

Right now in my case I'm using a JSON format.

To access and populate the select you can use javascript, more in particular JQuery would be handy, like this:

$.getJSON( "test.json", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "<option value='" + key + "'>" + val + "</option>" );
  });
});  

For further information check the official manual.

If you prefer to populate your dropdown on the server you could do something like this:

$json = file_get_contents('your_json_url');
$countries = json_decode($json);
foreach ($countries as $option){
  echo "<option value='" .$option[key]. "'>" .$option[$value]. "</option>";
}

If you want to do it from your databese the proccess is really similar as long as you also get an array.

If you still want to keep using your .txt format the @arkascha and @axiac answers are totally valid.

Hope this helped you ;)

Asur
  • 379
  • 3
  • 20
  • The question is clearly marked as [tag:php], you provided a Javascript solution. – axiac Mar 08 '16 at 15:23
  • @axiac Suit the task to the technology is never the best way, you should know that as the experience user you are, and he was actually clearly asking for advice and guidance. Anyway you are right, I will edit it and add a php function :) – Asur Mar 08 '16 at 15:25
  • @axiac Done editing into a more valid answer, thank you for the feedback – Asur Mar 08 '16 at 15:38
  • The answer was clearly about how to use a plain text file. It is questionable if judging against one format and praising another format makes sense, without you knowing anything about the situation. Typically such questions arise when the source data is provided by some external resource. In such cases first converting that to one of the formats you prefer makes no sense at all. Note: I say nothing against your suggestion, but why not simply answer what is asked? – arkascha Mar 08 '16 at 17:29
  • @arkascha I just thought answering this way could be more useful for the OP and all other user who may come by, at the end of the day if I ask something and there is a bad practice (not horrible, there are worse ones) I would like been told the correct way instead of just getting direct answers. So I won't delete this answer, despite of the score, just in case there is someone out there who think the same way as me – Asur Mar 09 '16 at 07:44
  • Don't get me wrong, I don't say what you wrote is wrong or that you should delete this answer. Also I did not downvote myself. But I stumble about statements like "there is a bad practice". Simply because that is an assumption. You don't know about the situation the OP is in, such judging about good and bad is a pretty long shot. I prefer to avoid it and stick with the given information instead of trying to _guess_ what _might_ be the case. – arkascha Mar 09 '16 at 08:51
  • @arkascha He posted he didn't know if it was even possible to access a .txt file so I naturally assume he needed some guidance... – Asur Mar 09 '16 at 08:55