简体   繁体   English

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

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

Would appreciate some assistance 希望得到一些帮助

i have a txt file witht he following contents: 我有一个txt文件,其中包含以下内容:

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

I want to delete the entry where the animal is "dog" living in an "house" 我想删除动物是“狗”住在“房子”里的条目

<?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/>';
        }
    }
}
?>

This successfully prints out the array without the entry where 'dog' and 'house' appears. 这样就可以成功打印出阵列,而不会出现'dog'和'house'出现的条目。 I need to write this back to the flat file though, but running into difficulties. 我需要把它写回平面文件,但遇到困难。

I have tried a variety of options include writting back to the file immediately when each entry is found. 我尝试了各种选项,包括在找到每个条目时立即写回文件。

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 

These are amongst the errors i have encountered. 这些是我遇到的错误之一。 Now from my understanding of arrays, 现在从我对数组的理解,
- when i go through this array called animal, - 当我通过这个名为animal的数组时,
- it checks index [0] for the two conditions and - 它检查索引[0]的两个条件和
- if the entry is not found, it assigns to to $a. - 如果未找到该条目,则分配给$ a。
- It then goes through the array starting at index [1], - 然后它从索引[1]开始经过数组,
- and so forth. - 等等。
Each time the new value is assigned to $a. 每次将新值分配给$ a。

I thought that printing it to file each time it appears might work, but this is where i get the fwrite and fclose errors above, and no idea how to resolve this (yet). 我认为每次出现它都可以将文件打印到文件中,但这是我在上面得到fwrite和fclose错误的地方,并且不知道如何解决这个问题。

I still have to do the bit where i need to replace 'apartment' with house, for one specifically selected entry, but will get there once I have sorted out the "delete" 我仍然需要做一些我需要用房子替换'公寓',一个特别选择的条目,但一旦我整理了“删除”就会到达那里

I dont need code, maybe just a logic flow that might assist me. 我不需要代码,也许只是一个可能对我有帮助的逻辑流程。

Thanks 谢谢

How about this for steps: 这个步骤怎么样:

  • Read the file. 阅读文件。
  • Store File contents in array. 将文件内容存储在数组中。
  • Remove item from array. 从数组中删除项目。
  • Overwrite the file with new contents. 用新内容覆盖文件。

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

What you can do is opening the source file in read mode and a temporary file in write mode. 您可以做的是在读取模式下打开源文件,在写入模式下打开临时文件。 As you read content from the "in" file, you write lines to the "out" file. 当您从“in”文件中读取内容时,您会在“out”文件中写入行。 When the "in" file is processed and closed, you rename "out" to "in". 处理并关闭“in”文件时,将“out”重命名为“in”。 This way you need to worry less about memory constraints. 这样您就不必担心内存限制。

When processing each line, it's better if you split on '|', so you know that the second element contains an animal name and the third element contains a housing name. 处理每一行时,如果你拆分'|'会更好,所以你知道第二个元素包含一个动物名称而第三个元素包含一个外壳名称。 Who knows if a cat is living in a doghouse. 谁知道一只猫是否住在狗窝里。

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

Although this doesn't answer your original question, I'd like to share what I've come up with. 虽然这不能回答你原来的问题,但我想分享一下我的想法。

I'm pretty sure this will do your entire script in three lines: 我很确定这会将你的整个脚本分成三行:

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

It uses a regex to replace the lines with dog|house , then writes the file back. 它使用正则表达式来替换dog|house的行,然后将文件写回。

  1. Read and dump all data until the one you want deleted into $array_1 . 读取并转储所有数据,直到要删除的数据为$array_1
  2. Read and dump rest of file into $array_2 . 读取并将文件的剩余部分转储到$array_2
  3. Concatenate 2 arrays in a $newarray , rewrite to original flatfile. $newarray连接2个数组,重写为原始flatfile。

Simple! 简单!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM