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


How do I read each line from a file in php?

我是学习php的新手,在我的第一个程序中,我想创建一个基本的php网站,具有登录功能以及用户和passwd的数组。

我的想法是将用户名存储为列表参数,并将 passwd 作为内容,如下所示:

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

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

data.txt sample:
username passwd
anotherUSer passwd

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

您可以使用

file()函数。

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

修改这个 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的新手,但最好的方法是将其存储在数据库中,并使用MD5或SHA1等算法加密密码,

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

$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];
}

看看这个线程。

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

$handle = @fopen("data.txt", "r");
if ($handle) {
    while (!feof($handle)) { 
        $line = stream_get_line($handle, 1000000, "'n"); 
        //Do Stuff Here.
    } 
fclose($handle);
}
使用 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];
}