PHP для цикла не читает файл - PullRequest
0 голосов
/ 27 февраля 2019

Итак, у меня есть веб-сайт, который я создаю вместе с курсом, и я столкнулся с проблемой.

Я пытаюсь прочитать содержимое файла .txt в цикл for, чтобы напечатать содержимое в выбор параметров формы.

Вот цикл for:

<p>
City Where You Want to Reside:<br />
<select name="city" size="1">
    <option value="-">-</option>

<?php
    $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];

    $filename = $DOCUMENT_ROOT.'data'.'cities.txt';

    $lines_in_file = count(file($filename));

    //print "<br>lines: ".$lines_in_file;

    $fp = fopen($filename, 'r');   //opens the file for reading

    $bool = file_exists($filename);

    if ($bool == true)
    {
        for ($ii = 1; $ii <= $lines_in_file; $ii++)
        {
            $line = fgets($fp);
            $file_city = trim($line);

            print '<option value="'.$file_city.'">'.$ii.':'.$file_city.'</option>';
        }

        fclose($fp);
    }
?>

</select>

Файл towns.txt содержит следующее:

Chicago
Detroit
Toronto
Los Angeles

Я ничего не получаю от опций, кроме "-".Я думаю, что проблема может заключаться в том, что он не может найти файл, потому что форма просто выводит опцию "-", а функция file_exists не находит файл и отменяет операцию.

Когда я "просмотр«Источник страницы», там написано, что код для выбора города должен быть следующим:

<font size='1'><table class='xdebug-error xe-warning' dir='ltr' border='1' 

cellspacing='0' cellpadding='1'>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Warning: file(C:/wamp64/wwwwww\datacities.txt): failed to open stream: No such file or directory in C:\wamp64\www\assignment_3.php on line <i>50</i></th></tr>
<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0101</td><td bgcolor='#eeeeec' align='right'>408544</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp64\www\assignment_3.php' bgcolor='#eeeeec'>...\assignment_3.php<b>:</b>0</td></tr>
<tr><td bgcolor='#eeeeec' align='center'>2</td><td bgcolor='#eeeeec' align='center'>0.0101</td><td bgcolor='#eeeeec' align='right'>408600</td><td bgcolor='#eeeeec'><a href='http://www.php.net/function.file' target='_new'>file</a>
(  )</td><td title='C:\wamp64\www\assignment_3.php' bgcolor='#eeeeec'>...\assignment_3.php<b>:</b>50</td></tr>
</table></font>
<br />
<font size='1'><table class='xdebug-error xe-warning' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Warning: count(): Parameter must be an array or an object that implements Countable in C:\wamp64\www\assignment_3.php on line <i>50</i></th></tr>
<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0101</td><td bgcolor='#eeeeec' align='right'>408544</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp64\www\assignment_3.php' bgcolor='#eeeeec'>...\assignment_3.php<b>:</b>0</td></tr>
</table></font>
<br />
<font size='1'><table class='xdebug-error xe-warning' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Warning: fopen(C:/wamp64/wwwwww\datacities.txt): failed to open stream: No such file or directory in C:\wamp64\www\assignment_3.php on line <i>54</i></th></tr>
<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0101</td><td bgcolor='#eeeeec' align='right'>408544</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp64\www\assignment_3.php' bgcolor='#eeeeec'>...\assignment_3.php<b>:</b>0</td></tr>
<tr><td bgcolor='#eeeeec' align='center'>2</td><td bgcolor='#eeeeec' align='center'>0.0118</td><td bgcolor='#eeeeec' align='right'>409328</td><td bgcolor='#eeeeec'><a href='http://www.php.net/function.fopen' target='_new'>fopen</a>
(  )</td><td title='C:\wamp64\www\assignment_3.php' bgcolor='#eeeeec'>...\assignment_3.php<b>:</b>54</td></tr>
</table></font>

Я заметил Warning: file(C:/wamp64/wwwwww\datacities.txt): failed to open stream: No such file or directory in C:\wamp64\www\assignment_3.php on line <i>50</i> и подумал, может ли проблема с wwwwww вызвать?Если да, то как мне это исправить?

Кстати, я использую WAMP для размещения этих файлов.Я также использую Notepad ++ для редактирования файлов PHP и .txt.

1 Ответ

0 голосов
/ 27 февраля 2019

Если текстовый файл находится в том же каталоге, что и файл PHP, просто не используйте путь.Если файл находится в подкаталоге data, например, используйте то, что ниже.Весь код может быть выполнен следующим образом:

$lines = file('data/cities.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach($lines as $ii => $file_city) {
    echo '<option value="'.$file_city.'">'.($ii+1).':'.$file_city.'</option>';
}

Независимо от того, как вы это делаете, вы не хотите загружать файл с file, а затем открывать его и читать его построчно,Просто прочитайте каждую строку до конца файла:

$ii = 1;
if($fp = fopen('data/cities.txt', 'r')) {
    while($line = fgets($fp)) {
        $file_city = trim($line);
        echo '<option value="'.$file_city.'">'.$ii.':'.$file_city.'</option>';
        $ii++;
    }
}
...