读取所有行都带分隔符的文本文件


Read textfile with delimiters at all lines

我有一个文本文件,看起来像这样:

NAME=ARTHUR
LASTNAME=McConnell
AGE=43

我要做的是得到一个像这样的数组:

Array (
 [NAME] => ARTHUR
 [LASTNAME] => McConnell
 [AGE] => 43
)

非常感谢所有的帮助

$filename = 'info.txt';
//Read the file into a line-by-line array
$contents = file($filename);
//Loop through each line
foreach($contents as $line) {
    //Split by the = sign
    $temp_array = explode('=', $line);
    //Rebuild new array
    $new_array[$temp_array[0]] = $temp_array[1];
}
//Print out the array at the end for testing
var_dump($new_array);

如果您的文件格式具有完全相同的语法,则可以使用parse_ini_file()。它不关心文件扩展名,所以你也可以在.txt文件上应用它,只要格式正确。

用法

NAME=ARTHUR
LASTNAME=McConnell
AGE=43

parser.php

<?php
$data = parse_ini_file('test.txt');
var_dump($data);

认为我已经在变量中给出了它

$variable = "NAME=ARTHUR
LASTNAME=McConnell
AGE=43"
//instead of this you can read the whole file
$lines = explode(PHP_EOL, $variable);

可以使用parse_ini_file

$data = parse_ini_file('myFile.txt');

或使用explode两次

// first in end of lines
$data = explode(PHP_EOL, file_get_contents('myFile.txt'));
// and after, make a loop on the resulting array and creating a new array
$arr = array();
foreach ($data as $row) {
    $line = explode("=", $row);
    $arr[$line[0]] = $line[1];
}