php - 将每行txt文件读取到新的数组元素
我试图将文本文件的每一行读入一个数组,并将每一行放在一个新元素中。
我的代码到目前为止。
$file = fopen("members.txt", "r");
$i = 0;
while (!feof($file)) {
$line_of_text = fgets($file);
$members = explode('\n', $line_of_text);
fclose($file);
?>
11个解决方案
375 votes
如果您不需要任何特殊处理,这应该是您正在寻找的
$lines = file($filename, FILE_IGNORE_NEW_LINES);
Yanick Rochon answered 2019-08-10T09:57:11Z
33 votes
我发现的最快方式是:
// 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。
根据您设置文本文件的方式,您可能需要使用\ n位。
Drew Dello Stritto answered 2019-08-10T09:57:52Z
24 votes
只要用这个:
$array = explode("\n", file_get_contents('file.txt'));
RoLife answered 2019-08-10T09:58:11Z
21 votes
$file = fopen("members.txt", "r");
$members = array();
while (!feof($file)) {
$members[] = fgets($file);
}
fclose($file);
var_dump($members);
?>
Gaurav answered 2019-08-10T09:58:28Z
20 votes
$yourArray = file("pathToFile.txt", FILE_IGNORE_NEW_LINES);
FILE_IGNORE_NEW_LINES避免在每个数组元素的末尾添加换行符
您也可以使用FILE_SKIP_EMPTY_LINES来跳过空行
这里参考
iianfumenchu answered 2019-08-10T09:59:06Z
7 votes
它很简单:
$lines = explode("\n", file_get_contents('foo.txt'));
file_get_contents() - 将整个文件作为字符串。
"\n" - 将使用分隔符"\r\n"拆分字符串 - 换行符的ASCII-LF转义是什么。
但要注意 - 检查文件是否有UNIX-Line结尾。
如果"\n"无法正常工作,你有另外编码2换行,你可以尝试"\r\n","\r"或"\025"
CodeBrauer answered 2019-08-10T10:00:02Z
6 votes
$lines = array();
while (($line = fgets($file)) !== false)
array_push($lines, $line);
显然,您需要先创建文件句柄并将其存储在$file中。
Rafe Kettler answered 2019-08-10T10:00:28Z
2 votes
$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);
Attila Nagy answered 2019-08-10T10:00:47Z
1 votes
$file = file("links.txt");
print_r($file);
这将接受txt文件作为数组。 所以写任何东西到links.txt文件(使用一行代表一个元素)之后,运行这个页面:)你的数组将是$ file
altayevrim answered 2019-08-10T10:01:12Z
0 votes
您走的是正确的轨道,但您发布的代码存在一些问题。 首先,while循环没有关闭括号。 其次,每次循环迭代都会覆盖$ line_of_text,这可以通过在循环中将=更改为。=来修复。 第三,你爆炸了文字字符' \ n' 而不是一个实际的换行符; 在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);
?>
Nick Andren answered 2019-08-10T10:01:42Z
0 votes
这里已经很好地介绍了这一点,但是如果你真的需要比这里列出的任何东西更好的性能,你可以使用这种使用\n的方法。
$Names_Keys = [];
$Name = strtok(file_get_contents($file), "\n");
while ($Name !== false) {
$Names_Keys[$Name] = 0;
$Name = strtok("\n");
}
请注意,这假设您的文件保存为\n作为换行符(您可以根据需要更新),并且它还将单词/名称/行存储为数组键而不是值,以便您可以将其用作 查找表,允许使用isset(更快,更快),而不是in_array。
Brian Leishman answered 2019-08-10T10:02:18Z