Stelio Kontos Stelio Kontos - 1 year ago 63
PHP Question

Issue in getting text content (php)

i'm actually working on Ubuntu distribution, coding php.

I want to read a text file, and extract lines so that they appear in a combobox field.

I'm trying to do it this way : (i'm new in php, be gentle :d)

$file = fopen($fichier_txt.'.txt', 'r+');

if ($file)
$compteur_lignes = 0;
while (!feof($file) /*&& ($buffer = fgets($file, 4096) !== false)*/)
$lignes = fgets($file);
echo '<br>';
echo $lignes;
echo '<br>';
$lignes = fgets($file);
echo '<select name="cbBox" size="1" id="Combobox">';
$option = "<option value=\"Please select a Category\">Select an option</option> \n";
for ($i = 0; $i < $compteur_lignes; $i++)

$option .= "<option ";
$option .= "value=\"$lignes[$i]\">$lignes[$i]</option> \n";
echo $option;
echo '</select>';


As I do this, i get the content of my text file in my localhost output, but my comboxo shows empty fields, like if my $lignes[$i] doesn't contain any value...

Would you mind helping me a little :) ?

Thanks in advance,


Stelio Kontos.

Answer Source

You are not filling $lignes as an array but as a string, which means that it always contains only the last line. You should be doing this:

$lignes = array();
while (!feof($file))
    $lignes[] = fgets($file);
    echo '<br>';
    echo $lignes[count($lignes) - 1];

And you have to remove the $lignes = fgets($file) that is outside your loop.

By the way, the variable $compteur_lignes is useless, you can get the size of the $lignes array at any time using the function count:

$lines_count = count($lignes);

As a side note that is slightly offtopic, I'd recommend naming your variables in english rather than french. PHP functions and keywords are in english, you should code in english.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download