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

时间:2012-02-07 20:37:49

标签: php file flat

非常感谢一些帮助

我有一个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'和'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错误的地方,并且不知道如何解决这个问题。

我仍然需要做一些我需要用房子替换'公寓'的地方,一个专门选择的条目,但是一旦我整理了“删除”就会到达那里

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

由于

6 个答案:

答案 0 :(得分:1)

步骤如何:

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

答案 1 :(得分:1)

为了节省一些时间,只有在从文件中读取验证规则时,才能将数据存储在数组中,并且在读完文件末尾后,您已准备好将数据写回文件。

答案 2 :(得分:0)

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

处理每一行时,如果你拆分'|'会更好,所以你知道第二个元素包含一个动物名称而第三个元素包含一个外壳名称。谁知道一只猫是否住在狗窝里。

答案 3 :(得分:0)

<?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 ... */
    }
?>

答案 4 :(得分:0)

虽然这不能回答你原来的问题,但我想分享一下我的想法。

我很确定这会将你的整个脚本分为三行:

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

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

答案 5 :(得分:0)

  1. 读取并转储所有数据,直到您要删除的数据为$array_1
  2. 读取并将文件的其余部分转储到$array_2
  3. $newarray中连接2个数组,重写为原始的flatfile。
  4. 简单!

相关问题