将txt文件的每一行读取到新的数组元素


Read each line of txt file to new array element

我正在尝试将文本文件的每一行读取到一个数组中,并将每一行都放入一个新元素中
到目前为止我的代码。

<?php
$file = fopen("members.txt", "r");
while (!feof($file)) {
$line_of_text = fgets($file);
$members = explode(''n', $line_of_text);
fclose($file);
?>

如果您不需要任何特殊处理,这应该可以满足您的需求

$lines = file($filename, FILE_IGNORE_NEW_LINES);

我找到的最快的方法是:

// Open the file
$fp = @fopen($filename, 'r'); 
// Add each line to an array
if ($fp) {
   $array = explode("'n", fread($fp, filesize($filename)));
}

其中$filename将是路径&文件名,例如../filename.txt.

根据您设置文本文件的方式,您可能需要重新设置。

只需使用此:

$array = explode("'n", file_get_contents('file.txt'));
$yourArray = file("pathToFile.txt", FILE_IGNORE_NEW_LINES);

FILE_IGNORE_NEW_LINES避免在每个数组元素的末尾添加换行符
您也可以使用FILE_SKIP_EMPTY_LINES跳过空行

此处引用

<?php
$file = fopen("members.txt", "r");
$members = array();
while (!feof($file)) {
   $members[] = fgets($file);
}
fclose($file);
var_dump($members);
?>

就这么简单:

$lines = explode("'n", file_get_contents('foo.txt'));

file_get_contents()-以字符串形式获取整个文件。

explode("'n")-将使用分隔符"'n"-换行符的ASCII-LF转义符来拆分字符串。

但请注意-检查文件是否有UNIX-行结尾。

如果"'n"不能正常工作,您有另一个换行符编码,您可以尝试"'r'n""'r""'025"

$lines = array();
while (($line = fgets($file)) !== false)
    array_push($lines, $line);

显然,您需要首先创建一个文件句柄,并将其存储在$file中。

$file = __DIR__."/file1.txt";
$f = fopen($file, "r");
$array1 = array();
while ( $line = fgets($f, 1000) )
{
    $nl = mb_strtolower($line,'UTF-8');
    $array1[] = $nl;
}
print_r($array);

您走在了正确的轨道上,但发布的代码出现了一些问题。首先,while循环没有结束括号。其次,每次循环迭代都会覆盖$line_of_text,这是通过将=更改为a.=来修复的消息灵通的第三,您正在分解文本字符"''n",而不是实际的换行符;在PHP中,单引号将表示文字字符,但双引号实际上将解释转义字符和变量。

    <?php
        $file = fopen("members.txt", "r");
        $i = 0;
        while (!feof($file)) {
            $line_of_text .= fgets($file);
        }
        $members = explode("'n", $line_of_text);
        fclose($file);
        print_r($members);
    ?>
    $file = file("links.txt");
print_r($file);

这将接受txt文件作为数组。因此,在links.txt文件中写入任何内容(对一个元素使用一行)之后,运行此页面:)您的数组将是$file

这里已经很好地介绍了这一点,但如果真的需要比这里列出的任何东西都更好的性能,则可以使用这种使用strtok的方法。

$Names_Keys = [];
$Name = strtok(file_get_contents($file), "'n");
while ($Name !== false) {
    $Names_Keys[$Name] = 0;
    $Name = strtok("'n");
}

注意,这假设您的文件以'n作为换行符保存(您可以根据需要进行更新),并且它还将单词/名称/行存储为数组键,而不是值,这样您就可以将其用作查找表,从而允许使用isset(快得多)而不是in_array