在文本文件中查找重复项

时间:2015-04-16 01:04:24

标签: php file text

我无法弄清楚如何解决这个“feof():3是无效的蒸汽资源”错误。我需要能够从用户和交叉引用中获取List.txt文件中的数据,并确保在写入之前不重复。 有什么建议吗?

<!DOCTYPE>
<html>
    <body>  
        <form action="List.php" method="POST">
        Name: <input type="text" name="name" /><br />
        Email: <input type="text" name="email" /><br />
        <input type="submit" name="save" value="Submit" /><br />
        <input type="submit" name="open" value="Open in Text Editor" /><br />
        </form>

    <?php
    $myArray = array();

    if (isset($_POST['save']))
    {
        $name = $_POST['name'];
        $email= $_POST['email'];
        $toString = $_POST['name']. " ". $_POST['email'];
        $fp = fopen("List.txt", 'w');
        while (!feof($fp)) {
           $line = fgets($fp);
           if(strcmp($toString,$line)==0) {
               echo "<h1>Duplicate entery.</h1>"; 
           }
           else {
               $fp1 = fopen("List.txt", 'a');   
               fwrite($fp, $name);
               fwrite($fp, $email);
               echo "<h1>Success. U have been added to list.</h1>";   
            }
            fclose($fp);
         }
      }
    ?>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

您正在关闭while循环中的流。将您的fclose($fp);移出循环,并将流模式设置为w+,如下所示:

$fp = fopen("List.txt", 'w+');
while (!feof($fp)) {
  $line = fgets($fp);
  if(strcmp($toString,$line)==0) {
    echo "<h1>Duplicate entery.</h1>"; 
  }
  else {
    $fp1 = fopen("List.txt", 'a');   
    fwrite($fp, $name);
    fwrite($fp, $email);
    echo "<h1>Success. U have been added to list.</h1>";   
  }
  //fclose($fp); move this out
}
fclose($fp);