Read txt file for Select

7

I want to use a select , with the data that is inside a .txt file, created by me. Use a function in PHP. Within the file ( select.txt ) I have:

teste1 
teste2 
teste3

And select

<select name=select >
    <option value=""></option>
    <option value=""></option>
    <option value=""></option>
</select>
    
asked by anonymous 19.11.2014 / 12:01

3 answers

8

For a few records you can use the file () function, it loads the entire file and lines in array.

<?php $linhas = file('teste.txt'); ?>
<select name=select >
    <?php foreach($linhas as $item){ ?>
           <option value=""><?php echo $item; ?></option>
    <?php } ?>
</select>

Another way to read a file is by combining the fopen () functions to open the file and < fgets () extracts content the second argument of the optional function informs the amount of bytes to be read.

/ p>
<?php $arquivo = fopen('teste.txt', 'r'); ?>
<select name=select >
    <?php while($linha = fgets($arquivo)){ ?>
           <option value=""><?php echo $linha; ?></option>
    <?php }
      fclose($arquivo);
     ?>
</select>
    
19.11.2014 / 12:14
6

The easiest way to do this is to use the file () function, it reads the file and returns a array containing for each position, a line of the read file.

In this way you will be able to read each line of the file and print the options within the select.

<select name='select'>
  <?php
    $arquivo = file("arquivo.txt");
    for($i = 0; $i < count($arquivo); $i++) {
      print "<option value=''>". $arquivo[$i] ."</option>";
    }
  ?>
</select>

To select a single line of the file use:

(Remember that in arrays the first position is 0)

print $arquivo[1]."<br>"; 
  

Retrieved from this link

    
19.11.2014 / 12:08
5

Use fopen to read the txt file line by line in an array here is a tutorial . The ideal I believe you have to play in an array or something like that to read separately, more to make the code beautiful, as it is here .

Then you can get this variable and perform a foreach within your select:

foreach($variavel as $linhas)
{
 $select = "<option value=''>".$linhas."</option>";
}
    
19.11.2014 / 12:18