PHP从文本文件中读取行

时间:2015-02-08 11:27:04

标签: php file io

我正在尝试在文本文件中搜索一行,然后打印以下三行。例如,如果文本文件有

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 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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逐行读取整个文件。 为什么打开文件要写?