2015-02-08 114 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