Read txt file for Select

Asked

Viewed 3,171 times

7

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

teste1 
teste2 
teste3

And the select

<select name=select >
    <option value=""></option>
    <option value=""></option>
    <option value=""></option>
</select>
  • Try to explain the question a little better so that it becomes more noticeable to help other users.

3 answers

8


For few records you can use the function file(), it loads the entire file and convert the lines of the 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 functions fopen() to open the file and fgets() extracts the contents of the second argument of the optional function informs the amount of bytes that must be read.

<?php $arquivo = fopen('teste.txt', 'r'); ?>
<select name=select >
    <?php while($linha = fgets($arquivo)){ ?>
           <option value=""><?php echo $linha; ?></option>
    <?php }
      fclose($arquivo);
     ?>
</select>
  • This answer saved the question +1

6

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

This way you will be able to read each line of the file and print the options within 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 file row use:

(Remembering that in arrays the first position is 0)

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

Taken from that link

5

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.