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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1372816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:15:32  来源:igfitidea点击:

How to get text from file into array in php

php

提问by Phil

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?

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

回答by Paul Dixon

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);

回答by Gumbo

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

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

回答by ?ystein Riiser Gundersen

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

Documentation

文档

回答by danielv

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 文件()