如何在php中读取文件中的每一行?

quhf5bfb  于 2023-06-20  发布在  PHP
关注(0)|答案(5)|浏览(100)

我刚开始学习php,在我的第一个程序中,我想做一个基本的php网站,具有登录功能,用户和密码数组。
我的想法是将用户名存储为列表参数,并将passwd作为内容,如下所示:

arr = array(username => passwd, user => passwd);

现在我的问题是,我不知道如何从文件(data.txt)中读取,以便将其添加到数组中。

data.txt sample:
username passwd
anotherUSer passwd

我已经用fopen打开了这个文件,并将其存储在$data中。

4nkexdtk

4nkexdtk1#

可以使用file()函数。

foreach(file("data.txt") as $line) {
    // do stuff here
}
yebdmbv4

yebdmbv42#

修改这个PHP示例(取自官方PHP站点... * 总是 * 检查第一!):

$handle = @fopen("/path/to/yourfile.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

致:

$lines = array();
$handle = @fopen("/path/to/yourfile.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        $lines[] = $buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

// add code to loop through $lines array and do the math...

请注意,您不应该将登录详细信息存储在未加密的文本文件中,这种方法存在严重的安全问题。我知道你是PHP新手,但最好的方法是将其存储在DB中,并使用MD5或SHA1等算法加密密码,

pxy2qtax

pxy2qtax3#

您不应该将敏感信息存储为明文,但为了回答您的问题,

$txt_file = file_get_contents('data.txt'); //Get the file
$rows = explode("\n", $txt_file); //Split the file by each line

foreach ($rows as $row) {
   $users = explode(" ", $row); //Split the line by a space, which is the seperator between username and password
   $username = $users[0];
   $password = $users[1];
}

Take a look at this thread.

bfrts1fy

bfrts1fy4#

这也适用于非常大的文件:

$handle = @fopen("data.txt", "r");
if ($handle) {
    while (!feof($handle)) { 
        $line = stream_get_line($handle, 1000000, "\n"); 
        //Do Stuff Here.
    } 
fclose($handle);
}
t30tvxxf

t30tvxxf5#

使用file()或file_get_contents()创建数组或字符串。
根据需要处理文件内容

// Put everything in the file in an array
$aArray = file('file.txt', FILE_IGNORE_NEW_LINES);

// Iterate throug the array
foreach ($aArray as $sLine) {

    // split username an password
    $aData = explode(" ", $sLine);

    // Do something with the username and password
    $sName = $aData[0];
    $sPass = $aData[1];
}

相关问题