PHP-从平面文件读取,删除行并写回平面文件


PHP - read from flatfile, remove line and write back to flat file

将提供帮助

我有一个包含以下内容的txt文件:

1234|dog|apartment|two
1234|cat|apartment|one
1234|dog|house|two
1234|dog|apartment|three

我想删除动物是住在"房子"中的"狗"的条目

<?php
if (isset($_POST['delete_entry]))
{
    //identifies the file
    $file = "db.txt";
    //opens the file to read
    @$fpo = fopen($file, 'r');
    //while we have not reached the end of the file
    while(!feof($fpo))
    {
        //read each line of the file into an array called animal 
        $animal[] = fgets($fpo);
    }
    //close the file
    fclose($fpo);
    //iterate through the array
    foreach ($animal as $a)
    {
        if the string contains dog and apartment
        if ((stripos ($a, 'dog']))&&(stripos ($a, 'house')))
        {
            //dont do anything            
        }
        else
        {
            //otherwise print out the string
            echo $a.'<br/>';
        }
    }
}
?>

这成功地打印出了数组,而没有出现"dog"answers"house"的条目。虽然我需要把这个写回平面文件,但遇到了困难。

我尝试了多种选择,包括在找到每个条目后立即写回文件。

Warning: feof() expects parameter 1 to be resource, boolean given in 
Warning: fwrite(): 9 is not a valid stream resource in
Warning: fclose(): 9 is not a valid stream resource in 

这些都是我遇到的错误。现在,根据我对数组的理解,
-当我穿过这个叫做动物的阵列时,
-它检查索引[0]是否满足这两个条件,并且
-如果找不到条目,则将分配给$a
-然后,它从索引[1]开始遍历数组,
-等等
每次将新值分配给$a时。

我认为每次出现时都将其打印到文件中可能会起作用,但这就是我得到上面的fwrite和fclose错误的地方,我还不知道如何解决这个问题。

对于一个特别选择的条目,我仍然需要用房子代替"公寓",但一旦我整理好"删除",我就会到达那里

我不需要代码,也许只是一个可能对我有帮助的逻辑流。

感谢

为了节省一些时间,只有当从文件中读取数据时,数据通过了验证规则,才可以将数据存储在数组中,并且在读取文件末尾后,数组就可以将其写回文件了。

步骤如下:

  • 读取文件
  • 将文件内容存储在数组中
  • 从数组中删除项
  • 用新内容覆盖文件

您可以在读取模式下打开源文件,在写入模式下打开临时文件。当您从"in"文件中读取内容时,您会向"out"文件写入行。处理并关闭"in"文件时,将"out"重命名为"in"。这样,您就不必担心内存限制了。

在处理每一行时,最好在"|"上拆分,这样您就知道第二个元素包含动物名称,第三个元素包含外壳名称。谁知道猫是不是住在狗窝里。

<?php
    $fileName = 'db.txt';
    $data = @file($fileName);
    $id = 0;
    $animal = "";
    $type = "";
    $number = 0;
    $excludeAnimal = array("dog");
    $excludeHouseType = array("house");
    foreach($data as $row) {
        list($id,$animal,$type,$number) = explode("|",$row);
        if(in_array($animal,$excludeAnimal) && in_array($type,$excludeHouseType))
            continue
        /* ... code ... */
    }
?>

虽然这不能回答您最初的问题,但我想分享一下我的想法。

我确信这将在三行中完成整个脚本:

$file = file_get_contents( 'db.txt');
$result = preg_replace('/^'d+'|dog'|house'|'w+$/m', '', $file);
file_put_contents( 'db.txt', $result);

它使用正则表达式将行替换为dog|house,然后将文件写回。

  1. 读取并转储所有数据,直到您想要删除的数据进入$array_1
  2. 读取文件的其余部分并将其转储到$array_2
  3. $newarray中连接两个数组,重写为原始平面文件

简单!