获取文本内容(php)的问题


Issue in getting text content (php)

我实际上在Ubuntu发行版上工作,编写php。

我想读取一个文本文件,并提取行,使它们出现在一个组合框字段。

我试着这样做:(我是php的新手,要温柔: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;
        $compteur_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>';
fclose($file);
}

当我这样做时,我在本地主机输出中获得文本文件的内容,但是我的组合框显示空字段,例如如果我的$lignes[$ I]不包含任何值…

你介意帮我一下吗?

提前感谢,

问候,

Stelio Kontos .

您没有将$lignes填充为数组,而是作为字符串填充,这意味着它始终只包含最后一行。你应该这样做:

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

你必须去除循环外的$lignes = fgets($file)

顺便说一下,变量$compteur_lignes是无用的,您可以随时使用count函数获得$lignes数组的大小:

$lines_count = count($lignes);

作为一个稍微偏离主题的旁注,我建议用英语而不是法语命名变量。PHP函数和关键字是英文的,你应该用英文编码。

我同意AntonieB的回答,但是代码需要修改一点才能工作。请试试这个:

$file = fopen($fichier_txt.'.txt', 'r+');
if ($file) 
{
    $lignes = array();
    while (!feof($file) /*&& ($buffer = fgets($file, 4096) !== false)*/)
    {
        $lignes[] = fgets($file);
        echo '<br>';
        echo end($lignes);
    }
    $lignes_count = count($lignes);
    echo '<select name="cbBox" size="1" id="Combobox">';
    $option = "<option value='"Please select a Category'">Select an option</option> 'n";
    for ($i = 0; $i < $lignes_count; $i++)
    {
        $option .= "<option ";
        $option .= "value='"$lignes[$i]'">$lignes[$i]</option> 'n";
    }
    echo $option;
    echo '</select>';
fclose($file);
}

希望对大家有所帮助