2012-02-07 69 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個數組,重寫爲原始平面文件。

簡單!