如何在php中从文件中获取文本到数组中

时间:2022-10-08 17:20:20

I have text file with some stuff that i would like to put into array. That text file has one value per line. How do i put each line into array?

我有一个文本文件,里面有一些我想放到数组中的东西。该文本文件每行有一个值。如何将每一行放入数组中?

6 个解决方案

#1


20  

use the file() function - easy!

使用file()函数-容易!

$lines=file('file.txt');

If you want to do some processing on each line, it's not much more effort to read it line by line with fgets()...

如果您想对每一行进行一些处理,那么使用fgets()逐行读取它并不会花费太多的精力……

$lines=array();
$fp=fopen('file.txt', 'r');
while (!feof($fp))
{
    $line=fgets($fp);

    //process line however you like
    $line=trim($line);

    //add to array
    $lines[]=$line;

}
fclose($fp);

#2


1  

use file()

使用文件()

http://se2.php.net/manual/en/function.file.php

http://se2.php.net/manual/en/function.file.php

#3


1  

$fileArr = file("yourfile.txt")

http://www.php.net/manual/en/function.file.php

http://www.php.net/manual/en/function.file.php

#4


0  

file will return an array of the file content where each element corresponds to one line of the file (with line ending character seqence).

文件将返回文件内容的数组,其中每个元素对应于文件的一行(行尾字符seqence)。

#5


0  

$lines = file('file.txt');

Documentation

文档

#6


0  

You can use file().

您可以使用文件()。

<?php
$file_arr = file(/path/file);
foreach ($lines as $line_num => $line) {
    echo "Line #{$line_num}: " . $line;
}
?>

php.net file()

php.net文件()

#1


20  

use the file() function - easy!

使用file()函数-容易!

$lines=file('file.txt');

If you want to do some processing on each line, it's not much more effort to read it line by line with fgets()...

如果您想对每一行进行一些处理,那么使用fgets()逐行读取它并不会花费太多的精力……

$lines=array();
$fp=fopen('file.txt', 'r');
while (!feof($fp))
{
    $line=fgets($fp);

    //process line however you like
    $line=trim($line);

    //add to array
    $lines[]=$line;

}
fclose($fp);

#2


1  

use file()

使用文件()

http://se2.php.net/manual/en/function.file.php

http://se2.php.net/manual/en/function.file.php

#3


1  

$fileArr = file("yourfile.txt")

http://www.php.net/manual/en/function.file.php

http://www.php.net/manual/en/function.file.php

#4


0  

file will return an array of the file content where each element corresponds to one line of the file (with line ending character seqence).

文件将返回文件内容的数组,其中每个元素对应于文件的一行(行尾字符seqence)。

#5


0  

$lines = file('file.txt');

Documentation

文档

#6


0  

You can use file().

您可以使用文件()。

<?php
$file_arr = file(/path/file);
foreach ($lines as $line_num => $line) {
    echo "Line #{$line_num}: " . $line;
}
?>

php.net file()

php.net文件()