2015-02-08 122 views
0

我試圖在文本文件中搜索一行,然後打印下面三行。例如,如果文本文件有PHP從文本文件讀取行

1413X 
Peter 
858-909-9999 
123 Apple road 

然後我PHP文件將通過形式參加的ID(「1413X」),把它比作在文本文件中的行 - 本質上是模擬數據庫 - 然後回聲以下三行。目前,它僅回顯電話號碼(後半部分數字錯誤?)。謝謝你的幫助。

<?php 
    include 'SearchAddrForm.html'; 

    $file = fopen("addrbook.txt", "a+"); 
    $status = false; 
    $data = ''; 


    if (isset($_POST['UserID'])) 
    { 
     $iD = $_POST['UserID']; 
     $contact = ""; 

     rewind($file); 

     while(!feof($file)) 
     { 
      if (fgets($file) == $iD) 
      { 
       $contact = fgets($file); 
       $contact += fgets($file); 
       $contact += fgets($file); 
       break; 
      } 
     } 

     echo $contact; 
    } 

    fclose($file); 
?> 
+2

php字符串連接運算符是'.'(點)不是'+'。 – georg 2015-02-08 11:35:26

回答

1

我做了什麼:

<?php 

//input (string) 
$file = "before\n1413X\nPeter\n858-909-9999\n123 Apple road\nafter"; 

//sorry for the name, couldn't find better 
//we give 2 strings to the function: the text we search ($search) and the file ($string) 
function returnNextThreeLines($search, $string) { 

    //didn't do any check to see if the variables are not empty, strings, etc 

    //turns the string into an array which contains each lines 
    $array = explode("\n", $string); 

    foreach ($array as $key => $value) { 
     //if the text of the line is the one we search 
     //and if the array contains 3 or more lines after the actual one 
     if($value == $search AND count($array) >= $key + 3) { 
      //we return an array containing the next 3 lines 
      return [ 
       $array[$key + 1], 
       $array[$key + 2], 
       $array[$key + 3] 
      ]; 
     } 
    } 

} 

//we call the function and show its result 
var_dump(returnNextThreeLines('1413X', $file)); 
+0

我的代碼不工作的主要原因是因爲在嘗試將它與iD匹配時,我沒有修剪()文件的行。無論如何,謝謝你的幫助。我從現在開始肯定會使用這個實現,因爲我不知道你可以將文件轉換爲數組。 – Peter 2015-02-08 12:51:37

+1

@PeterKuebler樂於助人。 我使用了一個字符串進行輸入,但是您可以使用[file_get_contents](http://php.net/file_get_contents)替換它,它將返回該文件的一個字符串。 – tleb 2015-02-08 12:57:45

1

最好是設置一些標誌,你發現ID和一些反算線後,實現你的目標。

<?php 
include 'SearchAddrForm.html'; 

// $file = fopen("addrbook.txt", "a+"); 
$file = fopen("addrbook.txt", "r"); 

$status = false; 
$data = ''; 


if (isset($_POST['UserID'])) 
{ 
    $iD = $_POST['UserID']; 
    $contact = ""; 

    rewind($file); 

    $found = false; 
    $count = 1; 
    while (($line = fgets($file)) !== FALSE) 
    { 
     if ($count == 3) // you read lines you needed after you found id 
      break; 

     if ($found == true) 
     { 
      $contact .= $line; 
      $count++ 
     } 

     if (trim($line) == $iD) 
     { 
      $found = true; 
      $contact = $line; 
     } 
    } 

    echo $contact; 
} 

fclose($file); 
?> 

這樣的例子如何實現這一點。正如你在評論中看到的,你應該使用$ contact。= value,而不是$ contact + = value。 而不是閱讀,你可以使用函數file逐行採取整個文件。 爲什麼要打開文件來寫?

+0

啊!問題是trim()!謝謝,這個代碼可能也會起作用。 – Peter 2015-02-08 12:52:22