2012-02-07 67 views
0

希望得到一些援助PHP - 从平面文件读取,删除线和写回平面文件

我有一个txt文件witht他以下内容:

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

这成功地打印出没有“狗”和“房子”出现的条目的数组。 虽然我需要将它写回平面文件,但遇到困难。

我已经尝试了各种选项,包括立即发回每个条目时写回文件。

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错误,不知道如何解决这个(还)。

我还是要做,我需要更换“公寓”有房子,一个专门所选条目的位,但会得到。有一次我已经整理出了“删除”

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

感谢

+0

为什么不使用数据库? – mosid 2013-05-30 12:24:24

回答

1

为了节省时间,你可以存储你的数据在阵列,只有当它通过你的验证规则时,它被从文件中读取,阅读文件结束后,你就会有阵准备写它回到文件。

+0

很难得到这个回声$ a。'
';回读到数组中。我所要做的只是fwrite($ pfile,$ a);它的工作。 – user1031551 2012-02-08 00:08:02

1

这个怎么样的步骤:

  • 读取文件。
  • 将文件内容存储在数组中。
  • 从阵列中移除物品。
  • 用新内容覆盖文件。
0

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

在处理每一行,它的更好,如果你劈在“|”,所以你知道,第二个元素包含一个动物名称和第三元素包含外壳名。谁知道一只猫是否住在狗窝里。

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

由于'in_array'执行线性搜索,因此这不是非常具有伸缩性,这很慢。 – nickb 2012-02-07 20:50:43

0

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

我敢肯定,这将做你的整个脚本三行:

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

它使用正则表达式与dog|house更换线路,然后写回文件。

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

简单!